如何绘制回归线

how to plot a regression line

我无法做出合适的回归线。我的 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()

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

尝试使用

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

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