2015-12-13 167 views
1

如何繪製一個Python熊貓多指標數據框作爲條形圖與組標籤?是否有任何繪圖庫直接支持這個?這SO post顯示了一個使用matplotlib的自定義解決方案,但有直接的支持嗎?繪製熊貓多指數條形圖

舉個例子:

quarter company 
Q1  Blue  100 
     Green  300 
Q2  Blue  200 
     Green  350 
Q3  Blue  300 
     Green  400 
Q4  Blue  400 
     Green  450 
Name: count, dtype: int64 

...可以在此數據幀可以用組標籤like this繪製?

由於提前,

拉菲

+0

下面的Goodword引用的[SO post](https://stackoverflow.com/questions/43545879/bar-chart-with-multiple-labels)解決了這個問題。 – rbinnun

回答

4
import pandas as pd 

data = pd.DataFrame([ 
     ('Q1','Blue',100), 
     ('Q1','Green',300), 
     ('Q2','Blue',200), 
     ('Q2','Green',350), 
     ('Q3','Blue',300), 
     ('Q3','Green',400), 
     ('Q4','Blue',400), 
     ('Q4','Green',450), 
    ], 
    columns=['quarter', 'company', 'value'] 
) 
data = data.set_index(['quarter', 'company']).value 

data.unstack().plot(kind='bar', stacked=True) 

stacked bar chart from multiindex

如果你不想你的堆疊條形圖:

data.unstack().plot(kind='bar') 

not-stacked bar chart

+0

Thanks @Goodword,標籤也可以分組嗎?像[這個圖表](https://i.stack.imgur.com/R5PJg.png)? – rbinnun

+0

當然。只是不要傳遞'stacked = True'參數。試試這個:'data.unstack()。plot(kind ='bar')' – Goodword

+1

我現在看到你發送的圖像中的標籤與我的修正有些不同。 [這SO帖子](https://stackoverflow.com/questions/43545879/bar-chart-with-multiple-labels)應該幫助你與這些標籤。 – Goodword