如何使用Pandas绘制条形图?

时间:2017-04-03 06:47:30

标签: python pandas matplotlib data-science

我有像这样的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

我尝试过使用pandas中的hist()函数,但是我无法弄清楚如何在条形图中包含标签以获得如下图形,如图中所示。

2 个答案:

答案 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

答案 1 :(得分: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

相关问题