2016-12-24 98 views
2

使用子图,是否有绘制每个子图的多条线的pythonic方法?我有一个熊猫数据框,有两个行索引,日期字符串和水果,存储列和数量的值。我想要5个小区,每个商店一个,日期字符串作为x轴,数量作为y轴,每个水果作为它自己的彩色线。Matplotlib:绘制每个时间序列子图中的多条线

df.plot(subplots=True) 

几乎让我在那里,我认为,与适量的小区,除了它聚合的数量完全,而不是水果阴谋。

enter image description here

回答

3

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

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 

enter image description here

首先,你要行索引的是第一级转换与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() 

enter image description here

我们可以

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

+0

@piRSqaured谢谢您绘制所有的人。非常有用的答案;我现在更好地掌握matplotlib的工作原理。 –

相关问题