我需要创建一个绘制线条的直方图,而不是步骤图或条形图。我正在使用 python 2.7 下面的 plt.hist 函数绘制了一条阶梯线,并且 bin 没有在 plt.plot 函数中对齐。
import matplotlib.pyplot as plt
import numpy as np
noise = np.random.normal(0,1,(1000,1))
(n,x,_) = plt.hist(noise, bins = np.linspace(-3,3,7), histtype=u'step' )
plt.plot(x[:-1],n)
我需要该行与垃圾箱中心的每个垃圾箱计数相关联,就好像有一个 histtype=u'line' 标志与align=u'mid' 标志一起使用
使用 scipy,您可以 使用
stats.gaussian_kde
估计概率密度函数:
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
noise = np.random.normal(0, 1, (1000, ))
density = stats.gaussian_kde(noise)
n, x, _ = plt.hist(noise, bins=np.linspace(-3, 3, 50),
histtype=u'step', density=True)
plt.plot(x, density(x))
plt.show()
您生成的线图未对齐,因为使用的 x 值是 bin 边缘。 您可以按如下方式计算 bin 中心:
bin_centers = 0.5*(x[1:]+x[:-1])
那么完整的代码将是:
noise = np.random.normal(0,1,(1000,1))
n,x,_ = plt.hist(noise, bins = np.linspace(-3,3,7), histtype=u'step' )
bin_centers = 0.5*(x[1:]+x[:-1])
plt.plot(bin_centers,n) ## using bin_centers rather than edges
plt.show()
如果您希望绘图填充到 y=0,则使用
plt.fill_between(bin_centers,n)
Matplotlib 的缩略图库 通常在像您这样的情况下非常有用。画廊中的 this 和 this one 的组合以及一些自定义可能非常接近您的想法:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
mu = 0
sigma = 1
noise = np.random.normal(mu, sigma, size=1000)
num_bins = 7
n, bins, _ = plt.hist(noise, num_bins, normed=1, histtype='step')
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.show()
此外,增加垃圾箱的数量也有帮助......