具有分类列数的分组条形图

时间:2021-04-01 08:48:00

标签: python

我有一个包含许多列的数据框,其中 2 个是 y 和 poutcome。它们都是分类数据。我根据 y 和子条形图 poutcome 制作了一个分组条形图。我试图通过这个结果创建一个组

y    poutcome
no   failure      427
     other        159
     success       46
     unknown     3368
yes  failure       63
     other         38
     success       83
     unknown      337

基于按数据框分组的结果,我认为它会产生一个看起来像这样的图形,图例和彩色条将失败、成功、其他和未知,它们将按是和否分组(例如图,4 和 5 是是和否)。你明白了。

g1

group by 是这个 bank.groupby(['y','poutcome'])['poutcome'].count() 但是显示像上面一样,我的显示像这样

enter image description here

我如何使它像第一张图一样?条形代表 poutcome,它们按 y

分组

2 个答案:

答案 0 :(得分:2)

您应该能够在绘图之前unstack(level=1)

grouped.unstack(level=1).plot.bar()

答案 1 :(得分:1)

这是我最初使用的数据框:

     y poutcome  count
0   no  failure    427
1   no    other    159
2   no  success     46
3   no  unknown   3368
4  yes  failure     63
5  yes    other     38
6  yes  success     83
7  yes  unknown    337

您应该可以通过设置 groupby

从您的 as_index=False 获取此信息

然后您可以使用 DataFrame.pivot 来排列绘图值:

df.pivot(index="poutcome", columns="y", values="count")
# y           no  yes
# poutcome           
# failure    427   63
# other      159   38
# success     46   83
# unknown   3368  337

# and plot that:
df.pivot(index="poutcome", columns="y", values="count").plot.bar()

enter image description here

或者在图例中使用 poutcome 交换索引和列参数:

df.pivot(index="y", columns="poutcome", values="count").plot.bar()

enter image description here

相关问题