【问题标题】:how to plot a regression line如何绘制回归线
【发布时间】:2016-05-12 11:40:05
【问题描述】:

我无法做出正确的回归线。我的 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 曲线是否不合适? NaN 最有可能发生,因为您将 missing_values 视为 NaN。
  • @HarryPotfleur 是的,我可以,但是很大,我如何为您提供数据?
  • @ToineKerckhoffs 我认为情节的图片在这种情况下会很有帮助。

标签: python numpy matplotlib regression


【解决方案1】:

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

尝试使用

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

(注意stage_ratM和dist_ratM的交换顺序)看看它现在是否有效。

【讨论】:

  • 谢谢,现在好多了,但仍然不好。看起来有更多的行,''a1,b1,c1''仍然没有意义。回归线的点是只有一行?我的数据文件很大(一百万个值),最 ''dis_rat' 为零,但可以对应于 ''stage_rat'' 的几个值。对我来说这很奇怪这是问题吗?现在是图表:@987654321 @
  • @ToineKerckhoffs 啊是的,在绘图之前根据 x 坐标(即 stage_ratM)对数据进行排序。 (具体来说,您可以使用 numpy.argsort 来获取排序后的索引,然后在调用 polyfit 之前使用这些索引对 dis_ratM 和 stage_ratM 进行排序。)并尝试为回归线和散点绘制不同的颜色,这样它就是明确哪个是哪个。
  • 对不起,我看不懂第二部分,如何使用索引对 dis_ratM 和 stage_ratM 进行排序?
  • @ToineKerckhoffs sort_ind = np.argsort(stage_ratM) 然后 stage_ratM = stage_ratM[sort_ind] 和 dis_ratM = dis_ratM[sort_ind]
  • 对不起,还有一个问题,我如何推断这条回归线?
猜你喜欢
  • 2021-03-18
  • 2018-07-10
  • 2017-01-21
  • 2014-02-20
  • 1970-01-01
  • 2017-06-12
  • 2015-01-15
  • 2020-11-01
  • 2021-11-23
相关资源
最近更新 更多