如何在 matplotlib "histogram" 图表上添加(或注释)值标签(或频率)

How to add (or annotate) value labels (or frequencies) on a matplotlib "histogram" chart

我想将频率标签添加到使用 plt.hist 生成的直方图中。

这是数据:

np.random.seed(30)
d = np.random.randint(1, 101, size = 25)
print(sorted(d))

我在 Whosebug 上查找了其他问题,例如: Adding value labels on a matplotlib bar chart 和他们的答案,但显然,plt.plot(kind='bar') 返回的对象与 plt.hist 返回的对象不同,我在使用 'get_height' 时出错或 'get width' 函数,如条形图的一些答案中所建议的那样。

同样,无法通过查看直方图上的 matplotlib 文档找到解决方案。 收到此错误

我是这样处理的。如果有人有一些建议来改进我的答案,(特别是 for 循环和使用 n=0、n=n+1,我认为必须有更好的方法来编写 for 循环而不必以这种方式使用 n),我会欢迎它。

# import base packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# generate data
np.random.seed(30)
d = np.random.randint(1, 101, size = 25)
print(sorted(d))

# generate histogram

# a histogram returns 3 objects : n (i.e. frequncies), bins, patches
freq, bins, patches = plt.hist(d, edgecolor='white', label='d', bins=range(1,101,10))

# x coordinate for labels
bin_centers = np.diff(bins)*0.5 + bins[:-1]

n = 0
for fr, x, patch in zip(freq, bin_centers, patches):
  height = int(freq[n])
  plt.annotate("{}".format(height),
               xy = (x, height),             # top left corner of the histogram bar
               xytext = (0,0.2),             # offsetting label position above its bar
               textcoords = "offset points", # Offset (in points) from the *xy* value
               ha = 'center', va = 'bottom'
               )
  n = n+1

plt.legend()
plt.show;