【问题标题】:How to make a bar plot of non-numerical data in pandas如何在熊猫中制作非数值数据的条形图
【发布时间】:2016-03-19 00:36:17
【问题描述】:

假设我有这些数据:

>>> df = pd.DataFrame(data={"age": [11, 12, 11, 11, 13, 11, 12, 11],
                        "response": ["Yes", "No", "Yes", "Yes", "Yes", "No", "Yes", "Yes"]})
>>> df
    age response
0   11  Yes
1   12  No
2   11  Yes
3   11  Yes
4   13  Yes
5   11  No
6   12  Yes
7   11  Yes

我想制作一个条形图,显示按年龄汇总的是或否响应。有可能吗?我试过histkind=bar,但都无法按年龄排序,而是分别绘制年龄和响应。

看起来像这样:

  ^
4 |   o
3 |   o
2 |   o
1 |   ox      ox      o
0 .----------------------->
      11      12      13  

其中o 是“是”,x 是“否”。

另外,是否可以将数字分组?例如,如果您的范围是 11 到 50,您可以将其放入 5 年的垃圾箱中。另外,是否可以在轴上或单个条形上显示百分比或计数?

【问题讨论】:

  • 使用 df.plot(kind='bar') 会给你的回复有 (11,No), (11,Yes),(12,No) 和以此类推。
  • df.plot(kind='bar'),不做任何事情,绘制一个以 y 为年龄的索引条形图。

标签: python pandas matplotlib seaborn


【解决方案1】:

要生成多条形图,您首先需要按年龄和响应分组,然后取消堆叠数据框:

df=df.groupby(['age','response']).size()
df=df.unstack()
df.plot(kind='bar')

这是输出图:

【讨论】:

  • 我收到了TypeError: Empty 'DataFrame': no numeric data to plot。但是,df 本身不是空的。
  • 有效!谢谢!您只需在df.groupby 之前添加df = 。另外,我有一个FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison return np.sum(name == np.asarray(self.names)) > 1。但那是 Pandas 的操作。我应该提交问题,还是我可以自己做点什么?
  • 看起来你使用的是旧版本的 Pandas,不用担心,它会在即将发布的版本中修复。
【解决方案2】:

bin 您的数据,请查看pandas.cut() see docs。对于分类图,我发现 seaborns 包非常有用 - see the tutorial on categorical plots。下面是一个示例,显示了您使用随机样本提到的箱的是/否计数:

df = pd.DataFrame(data={"age": randint(10, 50, 1000),
                    "response": [choice(['Yes', 'No']) for i in range(1000)]})

df['age_group'] = pd.cut(df.age, bins=[g for g in range(10, 51, 5)], include_lowest=True)
df.head()

   age response age_group
0   48      Yes  (45, 50]
1   31       No  (30, 35]
2   25      Yes  (20, 25]
3   29      Yes  (25, 30]
4   19      Yes  (15, 20]

import seaborn as sns
sns.countplot(y='response', hue='age_group', data=df, palette="Greens_d")

【讨论】:

  • 这太棒了。谢谢你。我用sns.countplot(x='age_group', hue='response', data=df.sort("response"), palette="Greens_d")
  • 另外,包的名称是seaborn,而不是seaborns
  • 已修复错字。看起来这解决了您问题的分箱和灌封方面。
猜你喜欢
  • 2017-04-18
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 2021-10-24
  • 2021-05-10
  • 2021-09-11
相关资源
最近更新 更多