# [SciPy-User] Adding a Best-Fit Line

Sat Feb 20 10:27:39 CST 2010

```Hi,

I'm trying to do a Q-Q plot for 2 sets of data (which will eventually
be uneven) against each other. I've tried my best to do the Q-Q plot
but when I try to do a best fit line it's nowhere near a best fit.
Could someone let me know how a best fit line is done?

Regards,

Mikey

import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sp
from scipy import stats
idata=np.array([6,2,6,0,5,8,8,5,2,4,5,8,5,8,6,4,4,8,7,4,6,1,6,7,0,-4,3,7,5,1,4,4,5,5,4,2,5,4,4,2,5,5,0,6,3,4,2,4,2,3,4,0,4,4,2,2,7,3,8,1,4,2,2,6-1,1,5,3,3,0,8,8,7,3,5,3,4,6,0,2-5,5,6,0,4,4,3,7,6,0,8,4,3,6-2,5,4,4,5,3,6,3,3,7,1])
pidata=np.array([3,0,3,2,3,6,6,4,4,4,4,7,5,1,3,4,4,8,1,4,6,-4,5,6,-3,-2,3,5,3,1,1,4,5,2,1,0,3,4,4,2,5,4,0,6,3,3,0,3,3,2,0,0,1,0,-2,5,6,2,0,1,1,0,1,4,-1,1,1,-1,0,1,4,4,4,3,4,3,3,4,0,-1,-5,3,4,-1,4,3,1,5,3,0,5,4,4,4,-4,3,2,2,5,3,5,3,2,4,1])
pidata=
P=np.arange(0,100,0.10)
Qx=stats.mstats.mquantiles(pidata,P)
Qy=stats.mstats.mquantiles(idata,P)
plt.plot(Qx, Qy, 'o', mec='black', mfc='green')
m = np.polyfit(Qx, Qy, 1)
yfit = np.polyval(m, Qx)
plt.plot(Qx, yfit, 'b--')
x1=-4.
x2=4.
y1=x1*m[0]+m[1]
y2=x2*m[0]+m[1]
plt.plot([x1,x2], [y1,y2], 'r--')
plt.text(4, -5.8, "Slope=%f, Offset=%f" % (m[0],m[1]))
plt.grid(True)
plt.show()
```