直方图
本课属于 Coddy Machine Learning 学习旅程的“数据与图表”单元。第 27 课,共 60 课。
十二次服务台来电的通话时长,单位为分钟。直方图可以展示这类数字的分布情况:它将数值范围分成相等的区间,并统计每个区间中的值:
calls = [2, 3, 3, 4, 5, 5, 6, 6, 6, 7, 9, 14]
fig, ax = plt.subplots()
counts, edges, bars = ax.hist(calls, bins=4)
print(counts)
print(edges)
plt.show()大多数调用需要 2 到 8 分钟。ax.hist 还会返回它统计的内容,因此会打印:
[4. 6. 1. 1.]
[ 2. 5. 8. 11. 14.]4 个区间需要 5 个 edges。落在边界上的值会进入右侧的区间,但最大值除外,它会留在最后一个区间。
挑战
中等果园称量了 120 个苹果,并将重量记录在 weights 中,单位为克。程序会读取分箱数量;起始代码会设置好带标题和标签的图表,并将其显示出来。
- 使用指定数量的分箱绘制
weights的直方图,并保留ax.hist返回的内容。 - 按下方所示,打印最满分箱的边界(四舍五入到小数点后 1 位)及其计数。
换一个果园并使用 6 个分箱时,程序会打印下面这一行,然后 Coddy 会描述图表:
Fullest bin: 153.6 to 167.8 g, 38 apples图表如下所示:
亲手试试
import numpy as np
import matplotlib.pyplot as plt
bins = int(input())
# 不要修改下面的代码行
rng = np.random.default_rng(11)
weights = rng.normal(150, 20, size=120)
fig, ax = plt.subplots()
ax.set_title("Apple Weights")
ax.set_xlabel("Weight (g)")
ax.set_ylabel("Apples")
# 在下面编写你的代码
# 不要修改下面的代码行
plt.show()
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
数据与图表中的所有课
自己练习: Python 在线编译器