2017-04-03 170 views
3

我有這樣如何使用Pandas繪製條形圖?

a b c d e f label 
1 3 4 5 6 7 1 
2 2 5 7 5 7 0 
4 7 9 0 8 7 1 
6 9 4 7 3 8 1 
7 0 9 8 7 6 0 

我想要的棒形圖看起來是這樣的熊貓數據幀 - :enter image description here

我一直在使用從大熊貓HIST()函數嘗試,但我不能圖我如何在條形圖中包含標籤以獲得如圖中所示的圖形。

+0

也許是有用的,以顯示創建您的樣本輸入,這樣我們就可以輕鬆地構建數據幀自己和測試,如果輸出是正確的命令。 –

+0

考慮你有上面的數據框。我用 –

回答

4

我認爲你需要pivot具有計數由cumcount 和最後呼叫DataFrame.plot.bar

df = pd.pivot(index=df.groupby('label').cumcount(), columns=df.label, values=df.a).fillna(0) 
print (df) 
label 0 1 
0  2.0 1.0 
1  7.0 4.0 
2  0.0 6.0 

df.plot.bar() 

graph1

或許需要骨料size與重塑通過unstack

df = df.groupby(['label', 'a']).size().unstack(0, fill_value=0) 

df.plot.bar() 

更好的樣品使用piRSquared數據:

graph2

+0

很酷的工作:-) thanku提出了可視化:) –

3

嘗試

df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar() 

考慮數據框df

np.random.seed([3,1415]) 
df = pd.DataFrame(
    np.random.randint(10, size=(50, 6)), 
    columns=list('abcdef') 
).assign(label=np.random.randint(2, size=50)) 

print(df.head()) 

    a b c d e f label 
0 0 2 7 3 8 7  0 
1 0 6 8 6 0 2  0 
2 0 4 9 7 3 2  0 
3 4 3 3 6 7 7  0 
4 4 5 3 7 5 9  1 

演示

df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar() 

enter image description here

+0

它工作:-) df.groupby('label').a.value_counts()。unstack(0,fill_value = 0).plot.bar()關於這一行你建議任何閱讀來理解的東西value_counts()函數? –

+0

@NiranjanAgnihotri [***'value_counts' ***](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html) – piRSquared

+0

如果我要動態繪製類似圖對於數據集中的所有屬性,我們在代碼行df.groupby('label')。a.value_counts()。unstack(0,fill_value = 0).plot.bar()中使用了屬性名稱。爲所有屬性動態執行此操作?將屬性名稱作爲字符串變量不起作用 –