如何使用 Pandas 绘制条形图?
How do I plot a bar graph using Pandas?
我有 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
我想要一个看起来像这样的条形图 - :
我已经尝试使用 pandas 中的 hist() 函数,但我无法弄清楚如何在条形图中包含标签以获得如下图所示的图像。
尝试
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()
我觉得你需要pivot
with counting by 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()
或者可能需要汇总 size
with reshape by unstack
:
df = df.groupby(['label', 'a']).size().unstack(0, fill_value=0)
df.plot.bar()
使用 piRSquared
数据以获得更好的样本:
我有 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
我想要一个看起来像这样的条形图 - :
我已经尝试使用 pandas 中的 hist() 函数,但我无法弄清楚如何在条形图中包含标签以获得如下图所示的图像。
尝试
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()
我觉得你需要pivot
with counting by 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()
或者可能需要汇总 size
with reshape by unstack
:
df = df.groupby(['label', 'a']).size().unstack(0, fill_value=0)
df.plot.bar()
使用 piRSquared
数据以获得更好的样本: