Matplotlib:每个时间序列子图绘制多条线

4
使用子图,是否有一种Pythonic的方法可以在每个子图中绘制多条线?我有一个带有两个行索引(datestring和fruit)的pandas数据帧,存储为列和数量为值。我想要5个子图,每个子图代表一个商店,其中datestring作为x轴,quantity作为y轴,每种水果都有自己的彩色线条。
df.plot(subplots=True)

几乎让我达到目标,只要加入适量的子情节,但它将所有数量汇总在一起,而不是按水果绘制。

enter image description here

1个回答

6

设置
始终提供可重现问题的示例数据。
我在此提供了一些示例数据。

cols = pd.Index(['TJ', 'WH', 'SAFE', 'Walmart', 'Generic'], name='Store')
dates = ['2015-10-23', '2015-10-24']
fruit = ['carrots', 'pears', 'mangos', 'banannas',
         'melons', 'strawberries', 'blueberries', 'blackberries']
rows = pd.MultiIndex.from_product([dates, fruit], names=['datestring', 'fruit'])
df = pd.DataFrame(np.random.randint(50, size=(16, 5)), rows, cols)
df

首先,您需要使用pd.to_datetime将行索引的第一层转换为日期格式。

enter image description here

df.index.set_levels(pd.to_datetime(df.index.levels[0]), 0, inplace=True)

现在我们可以直观地绘制图表。
# fill_value is unnecessary with the sample data, but should be there 
df.TJ.unstack(fill_value=0).plot()

在此输入图片描述

我们可以使用以下代码来绘制它们的图形:

fig, axes = plt.subplots(5, 1, figsize=(12, 8))

for i, (j, col) in enumerate(df.iteritems()):
    ax = axes[i]
    col = col.rename_axis([None, None])
    col.unstack(fill_value=0).plot(ax=ax, title=j, legend=False)

    if i == 0:
        ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', ncol=1)

fig.tight_layout()

enter image description here


@piRSqaured 谢谢。非常有帮助的回答;我现在更好地掌握了matplotlib的工作原理。 - hot_whisky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接