是否可以将数字放在 matplotlib 直方图之上?
Is it possible to put numbers on top of a matplot histogram?
import matplotlib.pyplot as plt
import numpy as np
randomnums = np.random.normal(loc=9,scale=6, size=400).astype(int)+15
输出:
array([25, 22, 19, 26, 24, 9, 19, 32, 30, 25, 29, 17, 21, 14, 17, 27, 27,
28, 17, 17, 20, 21, 16, 28, 20, 24, 15, 20, 20, 13, 33, 21, 30, 27,
8, 22, 24, 25, 23, 13, 24, 20, 16, 32, 15, 26, 34, 16, 21, 21, 28,
22, 23, 18, 20, 22, 23, 22, 23, 26, 22, 25, 19, 29, 14, 27, 21, 23,
24, 19, 25, 15, 22, 23, 19, 19, 23, 21, 22, 17, 25, 15, 24, 25, 23 ...
h = sorted(randomnums)
plt.hist(h,density=False)
plt.show()
输出:
根据我的研究,我只发现如何在条形图上绘制数字,但我想要的是在直方图上绘制。可能吗?
我在问题的评论中链接的 answer 的改编版本。非常感谢post!
下方评论中的建议
import matplotlib.pyplot as plt
import numpy as np
h = np.random.normal(loc=9,scale=6, size=400).astype(int)+15
fig, ax = plt.subplots(figsize=(16, 10))
ax.hist(h, density=False)
for rect in ax.patches:
height = rect.get_height()
ax.annotate(f'{int(height)}', xy=(rect.get_x()+rect.get_width()/2, height),
xytext=(0, 5), textcoords='offset points', ha='center', va='bottom')
...给出例如
import matplotlib.pyplot as plt
import numpy as np
randomnums = np.random.normal(loc=9,scale=6, size=400).astype(int)+15
输出:
array([25, 22, 19, 26, 24, 9, 19, 32, 30, 25, 29, 17, 21, 14, 17, 27, 27,
28, 17, 17, 20, 21, 16, 28, 20, 24, 15, 20, 20, 13, 33, 21, 30, 27,
8, 22, 24, 25, 23, 13, 24, 20, 16, 32, 15, 26, 34, 16, 21, 21, 28,
22, 23, 18, 20, 22, 23, 22, 23, 26, 22, 25, 19, 29, 14, 27, 21, 23,
24, 19, 25, 15, 22, 23, 19, 19, 23, 21, 22, 17, 25, 15, 24, 25, 23 ...
h = sorted(randomnums)
plt.hist(h,density=False)
plt.show()
输出:
根据我的研究,我只发现如何在条形图上绘制数字,但我想要的是在直方图上绘制。可能吗?
我在问题的评论中链接的 answer 的改编版本。非常感谢post!
下方评论中的建议import matplotlib.pyplot as plt
import numpy as np
h = np.random.normal(loc=9,scale=6, size=400).astype(int)+15
fig, ax = plt.subplots(figsize=(16, 10))
ax.hist(h, density=False)
for rect in ax.patches:
height = rect.get_height()
ax.annotate(f'{int(height)}', xy=(rect.get_x()+rect.get_width()/2, height),
xytext=(0, 5), textcoords='offset points', ha='center', va='bottom')
...给出例如