【问题标题】:Is there a clean way to generate a line histogram chart in Python?有没有一种干净的方法可以在 Python 中生成折线直方图?
【发布时间】:2026-01-17 12:40:01
【问题描述】:

我需要创建一个直方图来绘制一条线而不是阶梯图或条形图。我正在使用 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)

我需要这条线与 bin 中心的每个 bin 的计数相关,就好像 histt​​ype=u'line' 标志与 align=u'mid' 标志一起使用

【问题讨论】:

标签: python plot histogram


【解决方案1】:

使用 scipy,你可以 use stats.gaussian_kdeestimate the probability density function:

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()

【讨论】:

  • 这里的 y 轴是什么单位?是发生率的 %/100 还是某事。一样吗?
  • @Shushiro:曲线是概率分布的估计值。您可以将这些曲线视为已缩放以确保其曲线下方的面积为 1。
  • 这可以适用于密度=假的直方图吗?
  • 为什么我们需要u'step' 中的u
【解决方案2】:

您生成的线图没有对齐,因为使用的 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)

【讨论】:

    【解决方案3】:

    Matplotlib's thumbnail gallery 在像你这样的情况下通常很有帮助。来自画廊的thisthis 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()
    

    另外,增加垃圾箱的数量有助于...

    【讨论】:

    • 发现matplotlib.mlab去掉了normpdf()函数
    最近更新 更多