【问题标题】:how to print equation of line using scipy stats如何使用 scipy stats 打印线方程
【发布时间】:2014-07-30 14:55:10
【问题描述】:

我的代码对 2 组数据执行线性回归。它工作正常,但我不知道如何使用 scipy 或 numpy 将线的方程打印到图形本身。

这是我的代码:

y=np.array([15,1489,859,336,277,265,229,285,391,372,5,345])
x=np.array([196.16,17762.47,28542.19,30170.5,9384.06,43210.29,21819.2,16978.2,45767.54,12328.78,113.71,19257.6])

print x
print y

slope, intercept, r_value, p_value, slope_std_error = stats.linregress(x, y)
print "slope = "+ str(slope)
print "r_value = "+ str(r_value)
print "r_squared = " + str(r_value**2)
print "p_value = "+str(p_value)
# Calculate some additional outputs
predict_y = intercept + slope * x
print predict_y
pred_error = y - predict_y
degrees_of_freedom = len(x) - 2
residual_std_error = np.sqrt(np.sum(pred_error**2) / degrees_of_freedom)


# Plotting
pylab.xlabel('cost')
pylab.ylabel('signups')
pylab.plot(x, y, 'o')
pylab.plot(x, predict_y, 'k-')
pylab.show()

【问题讨论】:

    标签: python numpy matplotlib scipy regression


    【解决方案1】:

    有很多方法可以做到这一点,具体取决于您想要的外观。你可以有这条线的方程式:在旁边的一个盒子里;漂浮在地块中间;带有指向线的箭头(见下文);沿线写;作为标题;作为标题(即,通常出现在情节下方的文本中——这将是最常见的方法);或作为情节中的盒装图例(例如,不同颜色的线以不同的颜色命名)。

    在没有其他约束的情况下,我最喜欢的是指向直线的箭头,因为这样读者就不会怀疑等式实际上指的是什么。为此,请使用annotate:

    x0 = 20000
    y0 = slope*x0+intercept
    pylab.annotate(line_eqn, xy=(x0, y0), xytext=(x0-.4*x0, y0+.4*y0),
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5'))
    

    为了清楚起见,沿线书写似乎会更加清晰,但是对于垂直线或交叉线,这将难以阅读,并且定位灵活性较小。就我个人而言,我不推荐这个标题,因为读者希望在这个位置看到情节的实际标题或主题,但这可能是最容易做到的,因为它不需要其他参数来设置它的位置。

    【讨论】:

      【解决方案2】:

      你希望等式去哪里?把它放在标题上,例如:plt.title('$y=%3.7sx+%3.7s$'%(slope, intercept))。要将其放入情节中,请使用plot.text

      【讨论】:

      猜你喜欢
      • 2011-12-29
      • 2021-04-26
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多