Python 中对数刻度的线性回归图

Linear regression plot on log scale in Python

我想对x和y给出的数据做线性回归。当我使用线性图时,一切似乎都很好,但是当我想在对数刻度上绘制它时,这条线看起来不直。我想我应该将间隔划分为更细的网格,而不是只划分六个点。但是我做不到。

如何为以下脚本在对数刻度上进行线拟合?

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1560., 526., 408., 226., 448., 288.])
y = np.array([0.118, 0.124, 0.131, 0.160, 0.129, 0.138])

f = np.multiply(x,y**2)

coefs = np.polyfit(x, f, 1)

pred_f = coefs[1] + np.multiply(sorted(x), coefs[0])

fig, ax1 = plt.subplots(1, 1, figsize=(8,6))

ax1.scatter(x, f)
ax1.plot(sorted(x), pred_f, 'k--')
ax1.set_xscale('log')
ax1.set_yscale('log')

plt.show()

提前致谢。

确实,“直线”(线性函数)在 log-log 图上看起来并不直:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0.1, 10)
y = 2*x+3 # LINEAR!

plt.plot(x, y)
plt.xscale('log')
plt.yscale('log')
plt.show()

结果:


为了适应对数刻度,运行 您对原始数据的对数回归:

coefs = np.polyfit(np.log(x), np.log(f), 1)

# Now work with logarithms everywhere!
pred_f = coefs[1] + np.multiply(sorted(np.log(x)), coefs[0])

fig, ax1 = plt.subplots(1, 1, figsize=(8,6))
ax1.scatter(np.log(x), np.log(f)) # logs here too!
ax1.plot(sorted(np.log(x)), pred_f, 'k--') # pred_f is already in logs
plt.show()

剧情:

或者让 Matplotlib 绘制日志刻度。然后,您需要对 pred_f 求幂,以使其与数据处于相同的比例:

fig, ax1 = plt.subplots(1, 1, figsize=(8,6))
ax1.scatter(x, f) # original scale!
ax1.plot(sorted(x), np.exp(pred_f), 'k--') # exponentiate pred_f
ax1.set_xscale('log')
ax1.set_yscale('log')
plt.show()

绘图是一样的,但它现在使用数据的原始比例: