如何绘制回归线

时间:2016-02-03 10:20:36

标签: python numpy matplotlib regression

我无法做出正确的回归线。我的a1值应该是正数,但它是负数。如果我跳过掩码部分,那么我的a1,b1,c1值变为NaN。

kwargs = dict(delimiter = '\t',\
         skip_header = 0,\
         missing_values = 'NaN',\
         converters = {0:matplotlib.dates.strpdate2num('%d-%m-%Y %H:%M')},\
         dtype = float,\
         names = True,\
         )

ratingcats = np.genfromtxt('C:\Users\ker\Documents\Discharge_and_stageheight_Catsop.txt',**kwargs)

dis_rat = ratingcats['discharge']   #change names of collumns
stage_rat = ratingcats['stage']

#create regression line and mask NaN
dis_ratM = np.ma.masked_array(dis_rat,mask=np.isnan(dis_rat)).compressed()
stage_ratM = np.ma.masked_array(stage_rat,mask=np.isnan(dis_rat)).compressed()

a1,b1,c1 = polyfit(dis_ratM, stage_ratM, 2)

discharge_pred = polyval([a1,b1,c1],stage_ratM)

print (a1,b1,c1)

#create scatterplot

matplotlib.pyplot.scatter(stage_rat,dis_rat,color='red',label='Rating curve')
matplotlib.pyplot.plot(stage_ratM,discharge_pred,'r-',label='regression line')
matplotlib.pyplot.show()

1 个答案:

答案 0 :(得分:1)

第二次浏览你的代码后,我注意到polyfit的参数顺序错误。 polyfit的签名是numpy.polyfit(x, y, deg)

尝试使用

a1,b1,c1 = polyfit(stage_ratM, dis_ratM, 2)

(请注意stage_ratMdist_ratM的交换顺序),看看它现在是否有效。