【问题标题】:Plot a line graph over a histogram for residual plot in python在python中为残差图绘制直方图的折线图
【发布时间】:2016-01-13 22:56:03
【问题描述】:

我创建了一个脚本,用于在名为 nighttime 的数据框中绘制 NO2 与温度残差的直方图。

直方图显示了 Python 脚本中某处回归线的残差的正态分布。

我正在努力寻找一种在直方图上绘制钟形曲线的方法,如下例所示:

Plot Normal distribution with Matplotlib

如何获得残差直方图的拟合正态分布?

plt.suptitle('NO2 and Temperature Residuals night-time', fontsize=20)

WSx_rm = nighttime['Temperature']                                        
WSx_rm = sm.add_constant(WSx_rm)   
NO2_WS_RM_mod = sm.OLS(nighttime.NO2, WSx_rm, missing = 'drop').fit() 
NO2_WS_RM_mod_sr = (NO2_WS_RM_mod.resid / np.std(NO2_WS_RM_mod.resid)) 
#Histogram of residuals
ax = plt.hist(NO2_WS_RM_mod.resid)
plt.xlim(-40,50)
plt.xlabel('Residuals')
plt.show

【问题讨论】:

    标签: python plot histogram regression normal-distribution


    【解决方案1】:

    以下内容对您有用吗? (使用您提供的链接中的一些改编代码)

    import scipy.stats as stats
    
    plt.suptitle('NO2 and Temperature Residuals night-time', fontsize=20)
    
    WSx_rm = nighttime['Temperature']                                        
    WSx_rm = sm.add_constant(WSx_rm)   
    NO2_WS_RM_mod = sm.OLS(nighttime.NO2, WSx_rm, missing = 'drop').fit() 
    NO2_WS_RM_mod_sr = (NO2_WS_RM_mod.resid / np.std(NO2_WS_RM_mod.resid)) 
    #Histogram of residuals
    ax = plt.hist(NO2_WS_RM_mod.resid)
    plt.xlim(-40,50)
    plt.xlabel('Residuals')
    
    # New Code: Draw fitted normal distribution
    residuals = sorted(NO2_WS_RM_mod.resid) # Just in case it isn't sorted
    normal_distribution = stats.norm.pdf(residuals, np.mean(residuals), np.std(residuals))
    plt.plot(residuals, normal_distribution)
    
    plt.show
    

    【讨论】:

      【解决方案2】:

      您可以利用 seaborn 库中的方法绘制带有钟形曲线的分布。在您提供的示例中,我不清楚剩余变量。您可能会看到下面的代码 sn-p 仅供参考。

      # y here is an arbitrary target variable for explaining this example    
      residuals = y_actual - y_predicted 
      
      import seaborn as sns
      sns.distplot(residuals, bins = 10) # you may select the no. of bins
      plt.title('Error Terms', fontsize=20)           
      plt.xlabel('Residuals', fontsize = 15)     
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2020-06-19
        • 2012-02-07
        • 2013-07-17
        • 1970-01-01
        • 2020-01-23
        • 2019-11-18
        • 1970-01-01
        • 2011-08-21
        • 1970-01-01
        相关资源
        最近更新 更多