分类组的观测图数量

时间:2019-11-01 06:50:38

标签: python pandas matplotlib seaborn

我有一个看起来像-

的数据框
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)

1 个答案:

答案 0 :(得分:0)

听起来好像您想对观测值进行计数,而不是沿yaxis从列中绘制值。在seaborn中,其功能为countplot()

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

enter image description here

由于返回的对象是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)

enter image description here

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