有没有一种干净的方法可以在 Python 中生成线直方图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27872723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a clean way to generate a line histogram chart in Python?
提问by DanGoodrick
I need to create a histogram that plots a line and not a step or bar chart. I am using python 2.7 The plt.hist function below plots a stepped line and the bins don't line up in the plt.plot function.
我需要创建一个直方图来绘制一条线而不是一个步骤或条形图。我正在使用 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)
I need the line to correlate with each bin's count at the bin centers as if there was a histtype=u'line' flag to go with the align=u'mid' flag
我需要这条线与 bin 中心的每个 bin 的计数相关,就好像有一个 histtype=u'line' 标志与 align=u'mid' 标志一起使用
采纳答案by unutbu
Using scipy, you could use stats.gaussian_kde
to estimate the probability density function:
使用 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()
回答by mty
Matplotlib's thumbnail galleryis usually quite helpful in situations like yours. A combination of thisand this onefrom the gallery with some customizations is probably very close to what you have in mind:
Matplotlib 的缩略图库在像您这样的情况下通常非常有用。的组合这个和这个从画廊的一些自定义可能是非常接近你心目中是什么:
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()
Also, increasing the number of bins helps...
此外,增加垃圾箱的数量有助于...
回答by MattB
The line plot you are producing does not line up as the x values being used are the bin edges.
You can calculate the bin centers as follows: bin_centers = 0.5*(x[1:]+x[:-1])
Then the complete code would be:
您生成的线图未对齐,因为使用的 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()
If you want the plot filled to y=0 then use plt.fill_between(bin_centers,n)