使用Matplotlib

时间:2018-01-20 22:14:58

标签: python python-3.x numpy matplotlib

我一直在努力在使用Matplotlib和Python 3制作的半对数图上拟合直线。我已经看到了很多log-log比例数字的例子,但我尝试过的解决方案都没有(使用{{1 }})。这条线总是在某处弯曲。

以下是我到目前为止的情况:

numpy

关联的import os import matplotlib import matplotlib.pyplot as plt import numpy as np base_path = os.path.dirname(os.path.realpath(__file__)) fig = plt.figure() ax = fig.add_subplot(111) # Plot data. location = os.path.join(base_path, "data.csv") data = np.genfromtxt(location, delimiter=',', names=['year', 'bw']) ax.plot(data['year'], data['bw']) # Fit test. x = data['year'] y = data['bw'] y_ln = np.log10(y) n = data.shape[0] A = np.array(([[x[j], 1] for j in range(n)])) B = np.array(y_ln[0:n]) B = np.array(y[0:n]) X = np.linalg.lstsq(A, B)[0] a = X[0] b = X[1] fit = a * x + b p = np.polyfit(x, np.log(y), 1) ax.semilogy(x, p[0] * x + p[1], 'g--') ax.set_yscale('log') 文件如下所示:

data.csv

我获得的数字如下所示,其中拟合线是弯曲的。 Semi-log plot with fit which should be a straight line.

非常感谢您的反馈和建议。

1 个答案:

答案 0 :(得分:2)

如果您将数据的对数拟合到一条线上,则需要在实际绘制拟合数据时反转此操作。即如果您在np.log(y)上插入一行,则需要绘制np.exp(fit_result)

# Fit test.
x = data['year']
y = data['bw']

p = np.polyfit(x, np.log(y), 1)
ax.semilogy(x, np.exp(p[0] * x + p[1]), 'g--')

完整示例:

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

u = u"""2016, 68.41987090116676
2017, 88.9788618486191
2018, 90.94850458504749
2019, 113.20946182004333
2020, 115.71547492850719"""

data = np.genfromtxt(io.StringIO(u), delimiter=',', names=['year', 'bw'])

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(data['year'], data['bw'])

# Fit test.
x = data['year']
y = data['bw']

p = np.polyfit(x, np.log(y), 1)
ax.semilogy(x, np.exp(p[0] * x + p[1]), 'g--')

ax.set_yscale('log')

plt.show()

enter image description here