如何使用scipy stats打印线的方程

时间:2014-06-10 00:06:19

标签: python numpy matplotlib scipy regression

我的代码对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()

2 个答案:

答案 0 :(得分:6)

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

enter image description here

答案 1 :(得分:3)

有很多方法可以做到这一点,具体取决于你想要的外观。你可以得到直线方程:在一边的方框中;漂浮在情节中间;带箭头指向该线(见下文);沿着这条线写的;作为标题;作为标题(即,通常出现在情节下方的文本中 - 这将是最常见的方法);或作为图中的盒装图例(例如,使用不同颜色的不同颜色的线条)。

我最喜欢的,没有其他限制是箭头到线,因为那时读者毫不怀疑方程实际上指的是什么。为此,请使用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'))

enter image description here

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