numpy Python中对数尺度的线性回归图

6qqygrtg  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(97)

我想对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()
n6lpvg4x

n6lpvg4x1#

事实上,“直线”(线性函数)在双对数图上看起来并不直:

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绘制log ticks。然后,您需要对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()

图是相同的,但它现在使用数据的原始比例:

相关问题