【问题标题】:What is the difference between `np.histogram` and `plt.hist`? Why don't these commands plot the same graphics?`np.histogram` 和 `plt.hist` 有什么区别?为什么这些命令不绘制相同的图形?
【发布时间】:2013-12-30 03:16:45
【问题描述】:

更新:再次抱歉,由于 cmets 正确,代码已更新。而且图形仍然存在一些问题 - 一个历史被转移到另一个。

更新:对不起,这些历史记录有不同数量的垃圾箱。即使此时将“5”设置为plt.hist 中的垃圾箱数也无济于事

下面的代码计算同一数据源上的两个直方图。 绘制这些直方图表明它们并不重合。 np.hist 的标记:它返回两个数组的元组 - 包括边缘 bin 和计数在内的 bin 值。所以我认为将 bin 边缘位置的值居中是合理的。

import numpy as np
import matplotlib.pyplot as plt
s = [1,1,1,1,2,2,2,3,3,4,5,5,5,6,7,7,7,7,7,7,7]

xmin = 1
xmax = 7
step = 1.
print 'nbins=',(xmax-xmin)/step
print np.linspace(xmin, xmax, (xmax-xmin)/step)
h1 = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step))
print h1
def calc_centers_of_bins(x):
    return  list(x[i]+(x[i]-x[i+1])/2.0 for i in xrange(len(x)-1))

x = h1[1].tolist()
print x
y = h1[0].tolist()


plt.bar(calc_centers_of_bins(x),y, width=(x[-1]-x[0])/(len(y)), color='red', alpha=0.5)
plt.hist(s, bins=5,alpha=0.5)
plt.grid(True)
plt.show()

【问题讨论】:

  • 您正在使用不同的垃圾箱。 np.linspace(xmin, xmax, (xmax-xmin)/step) 有 5 个垃圾箱,但你告诉 plt.hist 使用 6 个。
  • @askewchan 你说得对,谢谢。但即使在这种情况下,情节也不重合……
  • 这是一个绘图问题,plt.bar 期望看到左边缘,而不是中心。请参阅我编辑的答案。
  • 顺便说一句,您说“np.histogram 的标记”是它返回值和 bin ...plt.hist 也是如此,它返回值、bin 边缘和绘图信息,所以你可以这样做:y, x, _ = plt.hist()_ 只是一个一次性变量)。

标签: python python-2.7 numpy matplotlib


【解决方案1】:

您在这两种情况下使用了不同的垃圾箱。在您的情况下,np.linspace(xmin, xmax, (xmax-xmin)/step) 有 5 个垃圾箱,但您告诉 plt.hist 使用 6 个垃圾箱。

您可以通过查看每个的输出来看到这一点:

h1 = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step))
h_plt = plt.hist(s, bins=6,alpha=0.5)

然后:

>>> h1[1]
array([ 1. ,  2.2,  3.4,  4.6,  5.8,  7. ])
>>> h_plt[1]
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.])

我会使用:

y, x = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step))
nbins = y.size
# ...
plt.hist(s, bins=nbins, alpha=0.5)

然后您的直方图匹配,但您的绘图仍然不匹配,因为您已将 np.histogram 的输出绘制在箱的中心,但 plt.bar 需要一个左边缘数组:

plt.bar(left, height, width=0.8, bottom=None, hold=None, **kwargs)

参数
----------
left:标量序列
条形左侧的x 坐标

height : 标量序列
条的高度

你想要的是:

import numpy as np
import matplotlib.pyplot as plt
s = [1,1,1,1,2,2,2,3,3,4,5,5,5,6,7,7,7,7,7,7,7]

xmin = 1
xmax = 7
step = 1
y, x = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step))

nbins = y.size

plt.bar(x[:-1], y, width=x[1]-x[0], color='red', alpha=0.5)
plt.hist(s, bins=nbins, alpha=0.5)
plt.grid(True)
plt.show()

【讨论】:

  • 现在我发现我的方法是错误地将垃圾箱的边缘居中。你直接跳过最后一个值就更清楚更简单了,非常感谢!
  • 欢迎您!我没有在答案中提到,但是要找到垃圾箱的中心,如果 x 是一个 numpy 数组(如果你不调用 x.tolist(),默认情况下它是,那么你可以说:centers = (x[1:] - x[:-1])/2.
  • 应该说 +:centers = (x[1:] + x[:-1])/2.
猜你喜欢
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 2011-04-10
  • 2019-05-18
  • 1970-01-01
  • 2013-06-14
  • 2020-06-28
相关资源
最近更新 更多