[英]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.