简体   繁体   English

在对数 - 对数图上绘制最佳拟合直线

[英]Plot straight line of best fit on log-log plot

Have some data that I've plotted on a log-log plot and now I want to fit a straight line through these points. 有一些数据我已经绘制在对数 - 对数图上,现在我想通过这些点拟合直线。 I have tried various methods and can't get what I'm after. 我尝试了各种方法,无法得到我想要的东西。 Example code: 示例代码:

import numpy as np
import matplotlib.pyplot as plt
import random

x= np.linspace(1,100,10)
y = np.log10(x)+np.log10(np.random.uniform(0,10))
coefficients = np.polyfit(np.log10(x),np.log10(y),1)
polynomial=np.poly1d(coefficients)
y_fit = polynomial(y)
plt.plot(x,y,'o')
plt.plot(x,y_fit,'-')
plt.yscale('log')
plt.xscale('log')

This gives me a ideal 'straight' line in log log offset by a random number to which I then fit a 1d poly. 这给了我一个理想的“直线”在log log偏移线上的一个随机数,然后我拟合了1d poly。 The output is: 输出是:

在此输入图像描述

So ignoring the offset, which I can deal with, it is not quite what I require as it has basically plotted a straight line between each point and then joined them up whereas I need a 'line of best fit' through the middle of them all so I can measure the gradient of it. 因此忽略我可以处理的偏移量,它不是我需要的,因为它基本上绘制了每个点之间的直线然后将它们连接起来,而我需要在它们中间的“最佳拟合线”所以我可以测量它的梯度。

What is the best way to achieve this? 实现这一目标的最佳方法是什么?

One problem is 一个问题是

y_fit = polynomial(y)

You must plug in the x values, not y , to get y_fit . 你必须插入x值,而不是y ,才能获得y_fit

Also, you fit log10(y) with log10(x) , so to evaluate the linear interpolator, you must plug in log10(x) , and the result will be the base-10 log of the y values. 另外,使用log10(x)拟合log10(y) ,因此要评估线性插值器,必须插入log10(x) ,结果将是y值的基数10对数。

Here's a modified version of your script, followed by the plot it generates. 这是您脚本的修改版本,后面是它生成的图表。

import numpy as np
import matplotlib.pyplot as plt
import random


x = np.linspace(1,100,10)
y = np.log10(x) + np.log10(np.random.uniform(0,10))

coefficients = np.polyfit(np.log10(x), np.log10(y), 1)
polynomial = np.poly1d(coefficients)
log10_y_fit = polynomial(np.log10(x))  # <-- Changed

plt.plot(x, y, 'o-')
plt.plot(x, 10**log10_y_fit, '*-')     # <-- Changed
plt.yscale('log')
plt.xscale('log')

情节

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

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