matplotlib 直方图:如何在条形图上显示计数?

新手上路,请多包涵

使用 matplotlib 的 hist 函数,如何让它在条形图上显示每个 bin 的计数?

例如,

 import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)

我们怎样才能让每个 bin 中的计数显示在它的条上?

原文由 xuhdev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 901
2 个回答

似乎 hist 不能这样做,你可以这样写:

 your_bins=20
data=[]
arr=plt.hist(data,bins=your_bins)
for i in range(your_bins):
    plt.text(arr[1][i],arr[0][i],str(arr[0][i]))

原文由 kiviak 发布,翻译遵循 CC BY-SA 3.0 许可协议

matplotlib 3.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 许可协议

推荐问题