python - 如何绘制 Pandas 计数的分组条形图

标签 python pandas matplotlib seaborn bar-chart

我有一个包含以下列的数据框:

gender     class

male       A
female     A
male       B
female     B
male       B
female     A

我想绘制一个双条形图,其中的列代表每个性别,值分别代表每个性别在 A 类和 B 类中的人数。

因此条形图应按性别分组,并且应该有 2 个条形图 - 每个类(class)一个。

我如何将其可视化?我看到这个例子,但我真的很困惑

speed = [0.1, 17.5, 40, 48, 52, 69, 88]
lifespan = [2, 8, 70, 1.5, 25, 12, 28]
index = ['snail', 'pig', 'elephant',
         'rabbit', 'giraffe', 'coyote', 'horse']
df = pd.DataFrame({'speed': speed,
                   'lifespan': lifespan}, index=index)

          speed  lifespan
snail       0.1       2.0
pig        17.5       8.0
elephant   40.0      70.0
rabbit     48.0       1.5
giraffe    52.0      25.0
coyote     69.0      12.0
horse      88.0      28.0

ax = df.plot.bar(rot=0)

enter image description here

我的索引只是第 0 行到第 # 行,所以我很困惑如何配置 df.plot.bar 来处理我的用例。任何帮助将不胜感激!

最佳答案

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {'gender': ['male', 'female', 'male', 'female', 'male', 'female'], 'class': ['A', 'A', 'B', 'B', 'B', 'A']}
df = pd.DataFrame(data)

# pivot the data and aggregate
dfp = df.pivot_table(index='gender', columns='class', values='class', aggfunc='size')

# plot
dfp.plot(kind='bar', figsize=(5, 3), rot=0)
plt.show()

enter image description here

plt.figure(figsize=(5, 3))
sns.countplot(data=df, x='gender', hue='class')
plt.show()

enter image description here

sns.catplot(kind='count', data=df, x='gender', hue='class', height=3, aspect=1.4)
plt.show()

关于python - 如何绘制 Pandas 计数的分组条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68900264/

相关文章:

python - 在 python 中绘制自定义图表

python - 在树中查找文件夹并创建包含其路径的列表

python - 如何从 "year","date","month","time"列生成unix时间列,最好使用python的pandas模块

python - 将 bool 检查与 & 结合起来不会 "short-circuts"吗?

python - 如何解决 pandas.get_dummies 中的问题

python - 如何处理有关将 int 应用于包含一项的系列的 FutureWarning?

python - 从html文档中提取日期

python - 从单行数据帧创建多行数据帧

python - 条形图 - 在一列 pandas 上绘制多行

Python - matplotlib 轴限制了大概的股票代码位置