【问题标题】:Plot number of observations for categorical groups绘制分类组的观察数
【发布时间】:2020-02-27 12:20:50
【问题描述】:

我的数据框看起来像 -

id      age_bucket          state           gender       duration       category1        is_active
1         (40, 70]     Jammu and Kashmir      m             123           ABB                1
2         (17, 24]       West Bengal          m             72            ABB                0
3         (40, 70]         Bihar              f            109            CA                 0
4         (17, 24]         Bihar              f             52            CA                 1
5         (24, 30]         MP                 m             23            ACC                1
6         (24, 30]         AP                 m             103           ACC                1
7         (30, 40]         West Bengal        f             182           GF                 0

我想创建一个条形图,其中包含每个 age_bucket 和状态(前 10 名)的活跃人数。对于性别和类别1,我想创建一个包含活跃人数比例的饼图。栏的顶部应显示活动和非活动成员的总数,并且类似地,百分比应显示在基于 is_active 的饼图中。

如何在 python 中使用 seaborn 或 matplotlib?

到目前为止我已经完成了 -

import seaborn as sns
%matplotlib inline 

sns.barplot(x='age_bucket',y='is_active',data=df)

sns.barplot(x='category1',y='is_active',data=df)

【问题讨论】:

  • 你用 matplotlib 标记了它,那么到目前为止你尝试了什么?使用 pyplot 会更容易,不是吗?

标签: python pandas matplotlib seaborn


【解决方案1】:

听起来您想计算观测值,而不是沿 y 轴绘制列中的值。在 seaborn 中,这个函数是 countplot():

sns.countplot('age_bucket', hue='is_active', data=df)

由于返回的对象是一个matplotlib轴,你可以将它分配给一个变量(例如ax),然后使用ax.annotate手动在图中放置文本:

ax = sns.countplot('age_bucket', hue='is_active', data=df)
ax.annotate('1      1', (0, 1), ha='center', va='bottom', fontsize=12)

Seaborn 无法创建饼图,因此您需要use matplotlib directly。但是,从条形图中判断计数和比例通常更容易,因此我通常建议您坚持使用这些,除非您有特定的限制迫使您使用饼图。

【讨论】:

    猜你喜欢
    • 2019-02-25
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多