gpt4 book ai didi

python - 使用 Matplotlib 在半对数刻度上拟合直线

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:31 24 4
gpt4 key购买 nike

我一直在努力在用 Matplotlib 和 Python 3 制作的半对数图上拟合一条直线。我见过很多对数对数比例图的例子,但我尝试过的解决方案都没有奏效(使用 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 文件如下所示:

2016, 68.41987090116676
2017, 88.9788618486191
2018, 90.94850458504749
2019, 113.20946182004333
2020, 115.71547492850719

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

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

最佳答案

如果你将数据的对数拟合成一条线,那么在实际绘制拟合数据时需要反转这个操作。 IE。如果您将一条线拟合到 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

关于python - 使用 Matplotlib 在半对数刻度上拟合直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48361637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com