使用 matplotlib 的 hist
函数,如何让它在条形图上显示每个 bin 的计数?
例如,
import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)
我们怎样才能让每个 bin 中的计数显示在它的条上?
原文由 xuhdev 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 matplotlib 的 hist
函数,如何让它在条形图上显示每个 bin 的计数?
例如,
import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)
我们怎样才能让每个 bin 中的计数显示在它的条上?
原文由 xuhdev 发布,翻译遵循 CC BY-SA 4.0 许可协议
有一个新的 plt.bar_label
自动标记条形容器的方法。
plt.hist
返回条容器作为第三个输出:
data = np.random.default_rng(123).rayleigh(1, 70)
counts, edges, bars = plt.hist(data)
# ^
plt.bar_label(bars)
如果您有分组或堆叠直方图, bars
将包含多个容器(每组一个),因此迭代:
fig, ax = plt.subplots()
counts, edges, bars = ax.hist([data, data * 0.3], histtype='barstacked')
for b in bars:
ax.bar_label(b)
请注意,您还可以通过 ax.containers
访问 bar 容器:
for c in ax.containers:
ax.bar_label(c)
原文由 tdy 发布,翻译遵循 CC BY-SA 4.0 许可协议
1 回答10.2k 阅读✓ 已解决
4 回答4.1k 阅读✓ 已解决
2 回答4.1k 阅读✓ 已解决
4 回答3.6k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
3 回答4.8k 阅读
1 回答4.3k 阅读✓ 已解决
似乎
hist
不能这样做,你可以这样写: