【问题标题】:Plotting two theoretical PDFs with each two histogram data set用每两个直方图数据集绘制两个理论 PDF
【发布时间】:2019-04-18 18:07:31
【问题描述】:

我正在尝试使用以下代码(来自Fitting a histogram with python)将两个直方图与两条 PDF 曲线拟合:

datos_A = df['KWH/hh (per half hour) ']
datos_B = df['Response KWH/hh (per half hour) ']
(mu_A, sigma_A) = norm.fit(datos_A)
(mu_B, sigma_B) = norm.fit(datos_B)
n, bins, patches = plt.hist([datos_A , datos_B], 16, normed=1)
y_A = mlab.normpdf(bins, mu_A, sigma_A)
y_B = mlab.normpdf(bins, mu_B, sigma_B)
l = plt.plot([bins, bins], [y_A, y_B], 'r--', linewidth=2)
plt.grid(True)
plt.show()

但是,我得到了这样的东西:

我得到的是那些垂直线,而不是每个直方图的两条 PDF 线。我尝试了很多方法来解决这个问题,但我仍然无法弄清楚。

调整我的代码后,我得到了这两条线,但是,它们不是平滑曲线。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这是因为plt.plot 逐行绘制每条曲线。这意味着根据您的示例,它绘制 n 条垂直线,因为所有线的 x 坐标均为 (bins[i], bins[i])

    要解决此问题,请更改行:

    l = plt.plot([bins, bins], [y_A, y_B], 'r--', linewidth=2)
    

    到:

    l_A = plt.plot(bins, y_A, 'r--', linewidth=2)
    l_B = plt.plot(bins, y_B, 'b--', linewidth=2)
    

    或者:

    l = plt.plot(bins, np.stack([y_A, y_B]).T, '--', lw=2)
    

    编辑

    要获得更平滑的线条,您可以像这样重新采样 bin:

    N_resample = 100
    bins_resampled = np.linspace(min(bins), max(bins), N_resample)
    y_A = mlab.normpdf(bins_resampled, mu_A, sigma_A)
    y_B = mlab.normpdf(bins_resampled, mu_B, sigma_B)
    l = plt.plot(bins_resampled, np.stack([y_A, y_B]).T, '--', lw=2)
    

    【讨论】:

    • 它解决了这个问题,但是,我想要一条令人窒息的线,因为这看起来更像是不同的直线连接而不是一条完整的曲线。我编辑了图片以澄清问题
    • 每个垃圾箱有一个点。如果你想要更多,你需要重新采样垃圾箱。
    • 我只想要 16 个柱状图的柱状图,但是否可以为曲线定义不同数量的柱状图?
    猜你喜欢
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2023-02-07
    • 2014-08-13
    • 2017-09-14
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多