Python 我如何绘制划分为类别的数据的相对频率?

Python 我如何绘制划分为类别的数据的相对频率?,python,python-3.x,pandas,matplotlib,Python,Python 3.x,Pandas,Matplotlib,我想根据一个类别标签得到人们权重的相对频率,然后将其绘制成一个条形图,如下所示: Weight Category 83.8 A 87.3 A 75.1 B 70.9 A 69.8 C 75.5 B ... ... 数据框如下所示: Weight Category 83.8 A 87.3 A 75.1 B 70.9 A 69.8 C 75.5 B ... ... 我曾想

我想根据一个类别标签得到人们权重的相对频率,然后将其绘制成一个条形图,如下所示:

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

数据框如下所示:

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()

使用
pd.cut
存储频率,使用
pd.crosstab
计数:

(pd.crosstab(pd.cut(df['Weight'], bins=np.linspace(0,100,10)),
             df['Category'])
   .plot.bar()
)

Seaborn是一个基于matplotlib的Python数据可视化库。它提供了一个高级界面,用于绘制有吸引力和信息丰富的统计图形。()

您将不会有与原始matplotlib相同的灵活性,但它可能只适合您,并为您提供强大的默认值

使用带有色调和multiple=dodge的histplot似乎可以满足您的需要。从官方文件


这看起来很有希望!但是,是否有方法将其转换为相对频率图?将normalize='index'传递到交叉表?谢谢,这是有效的。另外,您可以将'probability'传递到histplot函数的'stat'属性。