2016-12-24 124 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的工作原理。 –