`np.histogram` 和 `plt.hist` 有什么区别?为什么这些命令不绘制相同的图形?

aes*_*tet 5 python numpy matplotlib python-2.7

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

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

下面的代码在同一个数据源上计算两个直方图。绘制这些直方图表明它们并不重合。标记为np.hist:它返回一个由两个数组组成的元组 - 箱的值,包括边缘箱和计数数量。所以我认为将 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()
Run Code Online (Sandbox Code Playgroud)

图片

ask*_*han 7

您在两种情况下使用不同的垃圾箱。在您的情况下,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)
Run Code Online (Sandbox Code Playgroud)

然后:

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

我会用:

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

然后你的直方图匹配,但你的情节仍然不会,因为你已经np.histogram在 bin 的中心绘制了你的输出,但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()
Run Code Online (Sandbox Code Playgroud)

两个历史

  • 它应该说 +: 中心 = (x[1:] + x[:-1])/2。 (2认同)