Python 直接在图形上可视化matplotlib直方图箱数

Python 直接在图形上可视化matplotlib直方图箱数,python,numpy,matplotlib,histogram,Python,Numpy,Matplotlib,Histogram,我想我有一个简单的问题,但我看不到任何有帮助的博客显示如何实现这一点。我有一个名为“series”的python系列,我使用series.hist()来可视化直方图。我需要直接在图表上显示每个箱子的出现次数,但我找不到解决方案 如何在每个箱子的顶部看到一个标签,显示每个箱子的出现次数 准确地说,这是我的代码: import matplotlib.pyplot as plt your_bins=10 data = [df_5m_9_4pm.loc['2017-6']['sum_daily_cum_

我想我有一个简单的问题,但我看不到任何有帮助的博客显示如何实现这一点。我有一个名为“series”的python系列,我使用series.hist()来可视化直方图。我需要直接在图表上显示每个箱子的出现次数,但我找不到解决方案

如何在每个箱子的顶部看到一个标签,显示每个箱子的出现次数

准确地说,这是我的代码:

import matplotlib.pyplot as plt
your_bins=10
data = [df_5m_9_4pm.loc['2017-6']['sum_daily_cum_ret'].values]
plt.hist(data, binds = your_bins)
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]))
如果我只是简单地打印变量“data”,它就是这样的:

[array([ 0.        ,  0.03099187, -0.00417244, ..., -0.00459067,
         0.0529476 , -0.0076605 ])]
如果我运行上面的代码,我会收到错误消息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-97-917078981b1d> in <module>()
      2 your_bins=10
      3 data = [df_5m_9_4pm.loc['2017-6']['sum_daily_cum_ret'].values]
----> 4 plt.hist(data, binds = your_bins)
      5 arr = plt.hist(data,bins = your_bins)
      6 for i in range(your_bins):

~/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py in hist(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, normed, hold, data, **kwargs)
   3002                       histtype=histtype, align=align, orientation=orientation,
   3003                       rwidth=rwidth, log=log, color=color, label=label,
-> 3004                       stacked=stacked, normed=normed, data=data, **kwargs)
   3005     finally:
   3006         ax._hold = washold

~/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
   1708                     warnings.warn(msg % (label_namer, func.__name__),
   1709                                   RuntimeWarning, stacklevel=2)
-> 1710             return func(ax, *args, **kwargs)
   1711         pre_doc = inner.__doc__
   1712         if pre_doc is None:

~/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py in hist(***failed resolving arguments***)
   6205             # this will automatically overwrite bins,
   6206             # so that each histogram uses the same bins
-> 6207             m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
   6208             m = m.astype(float)  # causes problems later if it's an int
   6209             if mlast is None:

~/anaconda3/lib/python3.6/site-packages/numpy/lib/function_base.py in histogram(a, bins, range, normed, weights, density)
    665     if mn > mx:
    666         raise ValueError(
--> 667             'max must be larger than min in range parameter.')
    668     if not np.all(np.isfinite([mn, mx])):
    669         raise ValueError(

ValueError: max must be larger than min in range parameter.
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在()
2你的垃圾箱=10
3数据=[df_5m_9_4pm.loc['2017-6']['sum_daily_cum_ret']数值]
---->4 plt.hist(数据、绑定=您的存储库)
5 arr=plt.hist(数据、箱子=您的箱子)
范围内的i为6(您的_箱):
历史中的~/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot.py
3002 histtype=histtype,align=align,orientation=orientation,
3003 rwidth=rwidth,log=log,color=color,label=label,
->3004堆叠=堆叠,规范=规范,数据=数据,**kwargs)
3005最后:
3006 ax.\U hold=洗旧
内部的~/anaconda3/lib/python3.6/site packages/matplotlib/__init__.py(ax,*args,**kwargs)
1708警告。警告(消息%(标签名称,功能名称),
1709运行时警告,堆栈级别=2)
->1710返回函数(ax,*args,**kwargs)
1711预付款单=内部付款单__
1712如果pre_doc为无:
hist中的~/anaconda3/lib/python3.6/site-packages/matplotlib/axes//u axes.py(***解析参数失败***)
6205#这将自动覆盖垃圾箱,
6206#以便每个直方图使用相同的箱子
->6207米,料位=np。直方图(x[i],料位,重量=w[i],**hist_kwargs)
6208 m=m.astype(float)#如果是int,则稍后会导致问题
6209如果mlast为无:
直方图中的~/anaconda3/lib/python3.6/site-packages/numpy/lib/function\u base.py(a、箱子、范围、标准化、权重、密度)
665如果mn>mx:
666提升值错误(
-->667“范围参数中的最大值必须大于最小值”。)
668如果不是np.all(np.isfinite([mn,mx]):
669提升值错误(
ValueError:范围参数中的最大值必须大于最小值。
试试这个:

import matplotlib.pyplot as plt              
import numpy as np                                       


x = np.random.normal(size = 1000)                                         
counts, bins, patches = plt.hist(x, normed=True)
plt.ylabel('Probability')

# Label the raw counts and the percentages below the x-axis...
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
for count, x in zip(counts, bin_centers):
    # Label the raw counts
    plt.annotate('{:.2f}'.format(count), xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, 18), textcoords='offset points', va='top', ha='center')

plt.show()

如果您想要原始引用而不是频率,只需删除
normed=True
并可能更改格式字符串


我可能会补充说,您也可以通过复制代码并将
(0,-18)
更改为
(0,18)

@coldspeed来解决这个问题-该链接中的解决方案在我这边不起作用。我收到一条错误消息。使用该代码得到的错误消息是:“ValueError:max必须大于min in-in-range参数。”我重新打开了你的问题。
绑定
?可能是
垃圾箱
?@Georgy当我粘贴到这里时,这是一个输入错误。很好的捕获,但原始代码没有“绑定”。它仍然不起作用。否则,你们会知道至少一种方法,使用bin计数值来显示数组吗?如果我正在绘制频率,但想将原始计数显示为条形图的数据标签,有没有方法?