【问题标题】:How to add (or annotate) value labels (or frequencies) on a matplotlib "histogram" chart如何在 matplotlib“直方图”图表上添加(或注释)值标签(或频率)
【发布时间】:2020-11-21 19:27:56
【问题描述】:

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

这是数据:

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

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

同样,通过直方图上的 matplotlib 文档也找不到解决方案。 收到此错误

【问题讨论】:

标签: python matplotlib histogram frequency-distribution


【解决方案1】:

这是我的管理方法。如果有人有一些改进我的答案的建议,(特别是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;

【讨论】:

  • 在循环中使用 enumerate(),如下所示:for n, (fr, x, patch) in enumerate(zip(freq, bin_centers, patches)): 并去掉 n = 0n = n +1
  • 谢谢。有效。使用 enumerate 代替我使用的有什么优势吗?
  • 除了可迭代的项目之外,它只是提供了一个方便的自动递增循环计数器。这并不总是绝对必要的,但有助于在这种情况下简化语法。
猜你喜欢
  • 1970-01-01
  • 2022-01-21
  • 2011-08-14
  • 2019-08-21
  • 2015-05-09
  • 2020-01-27
相关资源
最近更新 更多