【发布时间】: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