簡體   English   中英

Plot 分類組的觀察數

[英]Plot number of observations for categorical groups

我有一個看起來像的數據框 -

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

我想創建一個條形圖 plot ,其中每個 age_bucket 和 state (前 10 名)有多少人處於活動狀態。 對於性別和類別1,我想創建一個包含活躍人數比例的餅圖。 欄的頂部應顯示活動和非活動成員的總數,類似地,百分比應顯示在基於 is_active 的餅圖上。

如何使用 seaborn 或 matplotlib 在 python 中做到這一點?

到目前為止我已經做了 -

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)

聽起來您想計算觀察結果,而不是沿 y 軸繪制列中的值。 在 seaborn 中,function 是countplot()

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

在此處輸入圖像描述

由於返回的 object 是 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 無法創建餅圖,因此您需要直接使用 matplotlib 但是,從條形圖中分辨計數和比例通常更容易,因此我通常建議您堅持使用這些,除非您有特定的限制迫使您使用餅圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM