我有一个包含以下列的数据框:
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)
我的索引只是第 0 行到第 # 行,所以我很困惑如何配置 df.plot.bar
来处理我的用例。任何帮助将不胜感激!
最佳答案
- 使用
pandas.DataFrame.pivot_table
至 reshape the dataframe从长格式到宽格式。索引将是 x 轴,当使用pandas.DataFrame.plot
绘制时,列将是组-
pd.crosstab(df['gender'], df['class'])
也可用于通过聚合进行 reshape 。
-
- 或者,使用
seaborn.countplot
和hue='class'
,或者图级版本seaborn.catplot
使用kind='count'
,两者都可以在不 reshape 数据帧的情况下创建所需的绘图。 - 如果所需的列之一在索引中,请指定
df.index
或使用df = df.reset_index()
重置索引
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()
plt.figure(figsize=(5, 3))
sns.countplot(data=df, x='gender', hue='class')
plt.show()
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/