Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在matplotlib上添加(或注释)值标签(或频率;直方图“;图表_Python_Matplotlib_Histogram_Frequency Distribution - Fatal编程技术网

Python 如何在matplotlib上添加(或注释)值标签(或频率;直方图“;图表

Python 如何在matplotlib上添加(或注释)值标签(或频率;直方图“;图表,python,matplotlib,histogram,frequency-distribution,Python,Matplotlib,Histogram,Frequency Distribution,我想将频率标签添加到使用plt.hist生成的直方图中 以下是数据: np.random.seed(30) d = np.random.randint(1, 101, size = 25) print(sorted(d)) 我在stackoverflow上查找了其他问题,如: 以及它们的答案,但很明显,plt.plot(kind='bar')返回的对象与plt.hist返回的对象不同,我在使用'get_height'或'get width'函数时出错,正如条形图的一些答案中所建议的那样 类似地

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

以下是数据:

np.random.seed(30)
d = np.random.randint(1, 101, size = 25)
print(sorted(d))
我在stackoverflow上查找了其他问题,如: 以及它们的答案,但很明显,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))


问题是什么?欢迎来到SO。这不是一个讨论论坛或教程。请花时间阅读和阅读该页面上的其他链接。此链接用于“条形”图表,不适用于“柱状图”:在循环中使用
enumerate()
,如下所示:
用于枚举中的n,(fr,x,patch)(zip(freq,bin_centers,patches)):
并摆脱
n=0
n=n+1
。谢谢。成功了。使用enumerate代替我使用的方法有什么好处吗?除了iterable的项之外,它还提供了一个方便的自动递增循环计数器。它并不总是绝对必要的,但在这种情况下有助于简化语法。
# 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;