【问题标题】:How to plot a histogram in matplotlib in python?如何在 python 的 matplotlib 中绘制直方图?
【发布时间】:2021-04-10 08:41:12
【问题描述】:

我知道如何在给出单个数据点时绘制直方图,例如: (33, 45, 54, 33, 21, 29, 15, ...)

通过简单地使用 matplotlib.pyplot.hist(x, bins=10)

但是如果我只有分组数据,例如:

等等。

我知道我可以通过更改xticks 来使用条形图来模拟直方图,但是如果我只想通过使用matplotlib.pyplothist 函数来做到这一点呢?

可以这样做吗?

【问题讨论】:

  • 表格格式不正常,所以我改用了图片

标签: python matplotlib histogram


【解决方案1】:

您可以手动构建hist() 参数并将现有值计数为weights

假设你有这个df

>>> df = pd.DataFrame({'Marks': ['0-10', '10-20', '20-30', '30-40'], 'Number of students': [8, 12, 24, 26]})
   Marks  Number of students
0   0-10                   8
1  10-20                  12
2  20-30                  24
3  30-40                  26

binsMarks 中的所有唯一边界值:

>>> bins = pd.unique(df.Marks.str.split('-', expand=True).astype(int).values.ravel())
array([ 0, 10, 20, 30, 40])

为每个 bin 选择一个 x 值,例如左边缘使其更容易:

>>> x = bins[:-1]
array([ 0, 10, 20, 30])

将现有值计数 (Number of students) 用作weights

>>> weights = df['Number of students'].values
array([ 8, 12, 24, 26])

然后将这些插入hist():

>>> plt.hist(x=x, bins=bins, weights=weights)

【讨论】:

    【解决方案2】:

    一种可能性是自己“取消分组”数据。

    例如,对于分数在 0 到 10 之间的 8 个学生,您可以生成 8 个值为 5(平均值)的数据点。对于标记在 10 到 20 之间的 12,您可以生成 12 个值为 15 的数据点。

    但是,“未分组”的数据只是真实数据的近似值。因此,最好只使用matplotlib.pyplot.bar 图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-14
      • 2012-01-12
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 2020-10-25
      • 2014-03-12
      • 2019-03-05
      相关资源
      最近更新 更多