2017-04-19 37 views
2

所以我想創建一個使用seaborn的barplot。我的數據的格式爲barplot X軸數據熊貓建設seaborn python

Packet number,Flavour,Contents 
1,orange,4 
2,orange,3 
3,orange,2 
4,orange,4 
... 
36, orange,3 
1, coffee,5 
2, coffee,3 
... 
1, raisin,4 
etc. 

我的代碼是目前:

revels_data = pd.read_csv("testtt.txt") rd = revels_data 

ax = sns.barplot(x="Packet number", y="Contents", data=rd) plt.show() 

我試圖創建其由顏色劃分的每個條的內部爲每個分組數條(在x軸) y軸上每個數據包的總內容的味道。

開始嘗試使每個數據包即總計

total_1 = (rd.loc[rd["Packet number"] == 1, "Contents"].sum()) 

,但不知道我怎麼會從那裏,或者如果有一個更簡單的方法來做到這一點。

任何意見是非常感謝!

回答

2

您想爲此使用hue。同樣,目前您正在顯示每個類別的平均值。要計算不同的功能,您可以使用estimator

因此,你的代碼應該是:

ax = sns.barplot(x="Packet number", y="Contents", hue="Flavour", data=rd) 

或者,如果你想顯示的總和,而不是平均:

ax = sns.barplot(x="Packet number", y="Contents", hue="Flavour", estimator=np.sum, data=rd) 

編輯

如果你對堆放的barplot感興趣,你可以直接使用熊貓,但你n首先把你的數據分組:

# Sum (or mean if you'd rather) the Contents per packet number and flavor 
# unstack() will turn the flavor into columns, and fillna will put 0 in 
# all missing columns 
grouped = rd.groupby(["Packet number", "Flavour"])["Contents"].sum().unstack().fillna(0) 

# The x axis is taken from the index. The y axis from the columns 
grouped.plot(kind="bar", stacked=True) 
+0

真棒,謝謝你這麼多。我怎麼做,而不是有每個味道多個酒吧,有一個酒吧內的風味部門在1酒吧? – mystifier

+0

我不認爲你可以用海豹做。但是,可以直接用'pandas'來完成。我將它添加到 – tmrlvi

+0

輝煌,謝謝 – mystifier