【问题标题】:How could I plot the relative frequency of data split into categories?我如何绘制数据分成类别的相对频率?
【发布时间】:2021-03-16 21:18:40
【问题描述】:

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

数据框如下所示:

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

【问题讨论】:

    标签: python python-3.x pandas matplotlib


    【解决方案1】:

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

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

    使用带有 hue 和 multiple=dodge 的 histplot 似乎可以满足您的需求。来自https://seaborn.pydata.org/generated/seaborn.histplot.html#seaborn.histplot的官方文档

    sns.histplot(data=tips, x="day", hue="sex", multiple="dodge", shrink=.8)
    

    【讨论】:

      【解决方案2】:

      使用pd.cut 存储您的频率,使用pd.crosstab 进行计数:

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

      【讨论】:

      • 这看起来很有希望!但是有没有办法将其转换为相对频率图?
      • 将 normalize='index' 传递给交叉表?
      • 此外,您可以将“概率”传递给 histplot 函数的“统计”属性。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 2018-08-15
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多