直接在图表上可视化matplotlib直方图的bin计数

3

请您好,我认为我的问题很简单,但我找不到任何有用的博客来展示如何实现。我有一个名为“series”的Python Pandas系列,并使用series.hist()来可视化直方图。我需要在图表上直接可视化每个bin的出现次数,但我找不到解决方法。

我该如何在每个bin上面看到显示每个bin的出现次数的标签呢?

要确切,请看我的代码:

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.

@coldspeed - 那个链接中的解决方案在我的端上不起作用。我收到了一个错误消息。 - Andrea
我使用该代码时收到的错误信息是:“ValueError:范围参数中的最大值必须大于最小值。” - Andrea
我已经重新开放了您的问题。 - cs95
绑定?也许是“bins”? - Georgy
@Georgy,这是我复制到这里时出现的一个笔误。你发现得真好,但原始代码没有“绑定”。它仍然无法工作。 否则,你们知道至少一种将数组与 bin 计数值配对的方法吗? - Andrea
从代码和您的data打印来看,似乎您已经将数据封装在一个列表中 - 因此,您正在传递一个数组的列表而不是值的数组。请尝试改为plt.hist(data[0], bins = your_bins)。或者更好的方法是在分配data时删除括号。 - Patrick O'Connor
1个回答

5

试试这个:

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) 来解决这个问题。


如果我正在绘制频率,但想要在条形图上显示原始计数作为数据标签 - 有没有办法做到这一点? - Chipmunk_da

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接