简体   繁体   English

如何在Python中绘制最佳拟合线

[英]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 ....我有大量的数据,我正在尝试以最佳拟合线对其进行绘制。 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. numpy.polyfit()x然后y作为其参数,因此您需要在调用它时交换varmed

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),'-')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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