2014-06-10 22 views
2

我的代碼對2組數據執行線性迴歸。它工作正常,但我不知道我怎麼可以打印圖形本身的線條方程式與scipy或numpy。如何使用scipy stats打印行方程

這裏是我的代碼:

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,.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() 

回答

5

你想去哪裏公式去?把它放在標題上,例如:plt.title('$y=%3.7sx+%3.7s$'%(slope, intercept))。把它放在劇情裏面使用plot.text

enter image description here

+0

$ y或%3.7s是什麼意思? – jxn

+0

@jenn,'$'告訴'matplotlib'繪製'mathtext'。 http://matplotlib.org/users/mathtext.html。 '%'是字符串格式化的一種方法,請參閱https://docs.python.org/2/library/stdtypes.html,第5.6.2節。 –

+0

我怎麼寫一個指數方程? – FaCoffee

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

爲清楚起見,它可能看起來沿線寫會更清楚,但這將獲得難以閱讀的垂直線或交叉線,而且定位靈活性較低。就我個人而言,我不會推薦這個標題,因爲讀者希望在這個位置看到劇情的真實標題或主題,但這可能是最容易做到的,因爲它不需要其他位置參數。