如何绘制按类别划分的数据相对频率图?

4
我想获取人们体重的相对频率,基于一个类别标签,然后将其作为条形图进行绘制,看起来类似于这样:

enter image description here

数据框的样式如下:

Weight   Category
83.8     A
87.3     A
75.1     B
70.9     A
69.8     C
75.5     B
...      ...

我考虑将每个类别的权重提取到自己的数据框中,并成功地获得了一个类别的相对频率,但我不确定如何将它们全部绘制在一起。

# This holds the total number of people in each category, with categories in alphabetical order
counts = df.groupby("Category")["Weight"].count()

catA = df.loc[df["Category"] == "A"]["Weight"].reset_index().drop(columns="index")
catA["bucket"] = pd.cut(catA["Weight"], 10)

newA = catA[["bucket", "Weight"]].groupby("bucket").count()
newE["relative"] = newE["Weight"] / counts[0]

ax = newA["relative"].plot(kind="bar", title="Relative Frequency of Weight for Category A")
ax.set(xlabel="Weight Bucket", ylabel="Relative Frequency (%)")
ax.tick_params(axis="x", labelrotation=45)
plt.show()
2个回答

2
Seaborn是一个基于matplotlib的Python数据可视化库。它提供了一个高级接口,用于绘制具有吸引力和信息量的统计图形。(链接1:https://seaborn.pydata.org/)
使用Seaborn可能不会像使用原始的matplotlib那样灵活,但也许它对您来说很有效,并提供了强大的默认设置。
使用带有hue和multiple=dodge的histplot似乎可以实现您所需的功能。请参考官方文档(链接2:https://seaborn.pydata.org/generated/seaborn.histplot.html#seaborn.histplot)。
sns.histplot(data=tips, x="day", hue="sex", multiple="dodge", shrink=.8)

seaborn


1
使用pd.cut对频率进行分组,使用pd.crosstab进行计数:
(pd.crosstab(pd.cut(df['Weight'], bins=np.linspace(0,100,10)),
             df['Category'])
   .plot.bar()
)

这看起来很有前途!不过有没有办法将其转换为相对频率图? - taway0282
1
将 normalize='index' 传递给交叉表? - Quang Hoang
此外,您可以将“probability”传递给histplot函数的“stat”属性。 - Canadian_Marine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接