繁体   English   中英

熊猫在散点图上绘制线性回归

[英]Pandas plotting linear regression on scatter graph

我正在尝试在散点图上绘制线性回归。

def chart1(df, yr, listcols):
    temp = df[(df['YEAR']==yr)]
    fig, axes = plt.subplots(nrows=2, ncols=2, figsize = (12,12))
    for e in [['WD','pk_h',0,0],['WD','of_h',0,1],['SAT','of_h',1,0],['SUN','of_h',1,1]]:
        temp.ix[(temp['daytype']==e[0])&(temp['hourtype']==e[1]),listcols].plot(kind='scatter', title=str(yr)+' '+e[0]+' '+e[1], x=listcols[0], y=listcols[1], ax=axes[e[2],e[3]])
    fig.tight_layout()
    return temp   

chartd = chart1(o2, 2017,['PROD', 'option_exercise'])

在此处输入图片说明

我不知道如何在我的循环中实现它。

它应该这样工作:

在for循环中运行回归并将结果存储在“ res”中。 使用存储的系数手动计算预测的y(“ yhat”)。 然后绘制x与y以及x与yhat的图表:

  import pandas.stats.api

  def chart4(df, yr, day, Y, sensi):
    temp = df[(df['YEAR']==yr)]
    temp = temp[(temp['daytype']==day)]
    fig = plt.figure(figsize=(15,13))
    for i, var in enumerate(sensi):
        res = ols(y=temp[Y], x=temp[var])
        label = 'R2: ' + str(res.r2)
        temp['yhat'] = temp[var]*res.beta[0] + res.beta[1]
        axis=fig.add_subplot(4,3,i+1)
        temp.plot(ax=axis,kind='scatter', x=var, y=Y, title=var)
        temp.plot(ax=axis, kind='scatter', x=var, y='yhat', color='grey', s=1, label=label)
        axis.set_xlabel(r'alpha', fontsize=18)
    fig.tight_layout()
    return

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM