2016-08-18 41 views
1

我想與熊貓一起製作多個堆積條形圖但我遇到了問題。下面是一個示例代碼:多重堆積條形圖與大熊貓

import pandas as pd 

df = pd.DataFrame({'a':[10, 20], 'b': [15, 25], 'c': [35, 40], 'd':[45, 50]}, index=['john', 'bob']) 

ax = df[['a', 'c']].plot.bar(width=0.1, stacked=True) 
ax=df[['b', 'd']].plot.bar(width=0.1, stacked=True, ax=ax) 
df[['a', 'd']].plot.bar(width=0.1, stacked=True, ax=ax) 

將會產生以下情節:

enter image description here

正如你所看到的,每個集羣內的酒吧都繪製在彼此的頂部,這是不是有什麼我想實現。我想讓同一個集羣內的條形圖彼此相鄰。我試圖玩弄「立場」的論點,但沒有取得太大的成功。

有關如何實現這一點的任何想法?

回答

3

你可以通過移動bar-plotposition參數做到這一點,使他們彼此相鄰,如圖所示:

matplotlib.style.use('ggplot') 

fig, ax = plt.subplots() 
df[['a', 'c']].plot.bar(stacked=True, width=0.1, position=1.5, colormap="bwr", ax=ax, alpha=0.7) 
df[['b', 'd']].plot.bar(stacked=True, width=0.1, position=-0.5, colormap="RdGy", ax=ax, alpha=0.7) 
df[['a', 'd']].plot.bar(stacked=True, width=0.1, position=0.5, colormap="BrBG", ax=ax, alpha=0.7) 
plt.legend(loc="upper center") 
plt.show() 

enter image description here

+0

我很困惑。該文件說,「職位」的論點從0到1,但你使用的值低於0和高於1.這是如何工作的? – fireboot

+2

不錯的觀察!正如你所知熊貓會繼承'matplotlib'對象中的關鍵字參數,你可以利用它來調整各種設置。其中一種情況是使用'matplotlib - bar'圖的'align'參數來改變'pandas - bar'圖的'position'參數。你也可以參考['源代碼'](https://github.com/pydata/pandas/blob/master/pandas/tools/plotting.py#L1904),它使用['align'](http:///matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar)選項,它允許設置* pos/neg *浮點數。 –

+1

好吧,如果我理解正確,它的工作原理是因爲在引擎蓋下,熊貓酒吧只是一個普通的matplotlib酒吧,其「對齊」屬性取值低於0和1以上。謝謝你的解釋! – fireboot