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

Matplotlib: Plot multiple lines per time series subplot

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

df.plot(subplots=True)

我认为,只要有适量的子图,我几乎就可以到达那里,只是它汇总了所有数量,而不是按水果绘制。

设置
始终提供重现您的问题的样本数据。
我在这里提供了一些

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

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()