【问题标题】:Grouped bar plot with categorical column count具有分类列数的分组条形图
【发布时间】:2021-04-01 08:48:00
【问题描述】:

我有这个数据框有很多列,其中 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 将是和否)。你明白了要点。

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

如何让它像第一张图一样?条形代表 poutcome,它们按 y 分组

【问题讨论】:

    标签: python


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

           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
      

      您应该可以通过设置 as_index=False 从您的 groupby 获取此信息

      然后您可以使用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()
      

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

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

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多