简体   繁体   English

在对数刻度上使用 matplotlib 拟合曲线

[英]Fit a curve using matplotlib on loglog scale

I am plotting simple 2D graph using loglog function in python as follows:我正在使用 python 中的 loglog 函数绘制简单的 2D 图,如下所示:

plt.loglog(x,y,label='X vs Y');

X and Y are both lists of floating numbers of n size. X 和 Y 都是n大小的浮点数列表。

I want to fit a line on the same graph.我想在同一张图上拟合一条线。 I tried numpy.polyfit , but I am getting nowhere.我试过 numpy.polyfit ,但我一无所获。

How do you fit a line using polyfit if your graph is already in loglog scale?如果您的图形已经在对数刻度中,您如何使用 polyfit 拟合一条线?

Numpy doesn't care what the axes of your matplotlib graph are. Numpy 不关心你的 matplotlib 图的轴是什么。

I presume that you think log(y) is some polynomial function of log(x) , and you want to find that polynomial?我假设您认为log(y)log(x)多项式函数,并且您想找到该多项式? If that is the case, then run numpy.polyfit on the logarithms of your data set:如果是这种情况,请对数据集的对数运行numpy.polyfit

import numpy as np
logx = np.log(x)
logy = np.log(y)
coeffs = np.polyfit(logx,logy,deg=3)
poly = np.poly1d(coeffs)

poly is now a polynomial in log(x) that returns log(y) . poly现在是log(x)中返回log(y)的多项式。 To get the fit to predict y values, you can define a function that just exponentiates your polynomial:为了得到预测y值的拟合,您可以定义一个只对多项式取幂的函数:

yfit = lambda x: np.exp(poly(np.log(x)))

You can now plot your fitted line on your matplotlib loglog plot:您现在可以在 matplotlib loglog图上绘制拟合线:

plt.loglog(x,yfit(x))

And show it like this并像这样显示

plt.show()

np.log(x) extracts the natural logarythm, so the fitting of the above solution is done on natural logs, while plt.loglog draws on 10-base logs. np.log(x)提取自然对数,因此上述解的拟合是在自然对数上完成的,而plt.loglog在 10 基对数上绘制的。

Both operations should be run in the same base:这两个操作应该在同一个基础上运行:

logx = np.log10(x)
logy = np.log10(y)

and

yfit = lambda x: np.power(10, poly(np.log(x)))

or要么

yfit = lambda x: 10**(poly(np.log(x)))

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

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