小编aes*_*tet的帖子

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

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

更新:对不起,这些历史记录有不同数量的 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)

图片

python numpy matplotlib python-2.7

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

matplotlib ×1

numpy ×1

python ×1

python-2.7 ×1