简体   繁体   中英

How to plot the best fit line in Python

I'm really confused :I .... I have a ton of data and I'm trying to plot it with a best fit line. I tried two different ways:

pl.plot(med[::skip],var[::skip],'k.')
p, q = np.polyfit(var[::skip],med[::skip], 1)
pl.plot(med,p*med+q,'-')

and

pl.plot(med[::skip],var[::skip],'k.')
p = np.polyfit(var[::skip],med[::skip], 1)
fit = np.polyval(p, var[::skip])
pl.plot(var[::skip],fit)

but they both give me something crazy:

在此处输入图片说明

what am I doing wrong?

numpy.polyfit() takes x then y as its arguments, so you need to swap var and med in your calls of it.

Note that because you have a log-log plot, this won't give you a straight line. Instead, you should fit to the log of the two variables:

pl.plot(med[::skip],var[::skip],'k.')
p, q = np.polyfit(np.log10(med[::skip]),np.log10(var[::skip]), 1)
pl.plot(med[::skip],10**(p*np.log10(med[::skip])+q),'-')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM