python 如何在 matplotlib 中绘制直方图?

How to plot a histogram in matplotlib in python?

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

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

但是如果我只有这样的分组数据怎么办:

| Marks    |Number of students |
| -------- | ----------------- |
| 0-10    | 8               |
| 10-20  | 12           |
|  20-30       |    24         |
|  30-40       |    26         |
|  ......       | ......            | 等等。

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

可以这样做吗?

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

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

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

您可以手动构建 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)