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

hot*_*sky 3 python plot matplotlib pandas plotly

使用子图,是否有一种pythonic方法来绘制每个子图的多行?我有一个pandas数据框,有两个行索引,datestring和fruit,包含列的存储和值的数量.我想要5个子图,每个商店一个,日期字符串作为x轴,数量作为y轴,每个水果作为自己的彩色线.

df.plot(subplots=True)
Run Code Online (Sandbox Code Playgroud)

我认为,几乎让我有适量的子图,除了它完全聚合数量而不是通过水果绘图.

在此输入图像描述

piR*_*red 5

安装程序
始终提供可重现问题的样本数据.
我在这提供了一些

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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

首先,您希望将行索引的第一级转换为 pd.to_datetime

df.index.set_levels(pd.to_datetime(df.index.levels[0]), 0, inplace=True)
Run Code Online (Sandbox Code Playgroud)

现在我们可以看到我们可以直观地绘制

# fill_value is unnecessary with the sample data, but should be there 
df.TJ.unstack(fill_value=0).plot()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我们可以用它们绘制所有这些

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述