如何在matplotlib中扩展线性回归图

2024-09-27 09:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个问题,试图拟合直线到线性的部分我的阴谋。 为了完成我的绘图,我必须延伸红线,就像它是一条直线一样,这样至少可以观察到它与x轴的交点

我的代码是:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

#data = pd.read_csv("LPPII_cw_2_1.csv")

#f = data["f [kHz]"] 
f = (1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 500)

#h21e = data["h21e [A/A]"]
h21e = (218., 215., 210., 200., 189., 175., 165., 150., 140., 129., 120., 69., 30.)

linearf = f[-3:]
linearh = h21e[-3:]

logA = np.log(linearf)
logB = np.log(linearh)

m, c = np.polyfit(logA, logB, 1, w=np.sqrt(linearh))
y_fit = np.exp(m*logA + c)

fig, ax = plt.subplots()

ax.set_xscale('log')
ax.set_yscale('log')

ax.set_xlabel('f [kHz]')
ax.set_ylabel('h$_{21e}$ [A/A]')

ax.scatter(f, h21e, marker='.', color='k')
ax.plot(linearf, y_fit, color='r', linestyle='-')

plt.show()

我的情节是这样的:

plot image


Tags: csvimportlogdataasnppltax
1条回答
网友
1楼 · 发布于 2024-09-27 09:32:28

您可以添加x轴的最大值,并将其附加到linearf的末尾。然后计算曲线,并绘制它。需要保存并重置旧的y限制,以防止matplotlib自动扩展这些限制。请注意,x-LIM只能在绘制散点图后提取

import matplotlib.pyplot as plt
import numpy as np

f = (1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 500)
h21e = (218., 215., 210., 200., 189., 175., 165., 150., 140., 129., 120., 69., 30.)

linearf = f[-3:]
linearh = h21e[-3:]

logA = np.log(linearf)
logB = np.log(linearh)

m, c = np.polyfit(logA, logB, 1, w=np.sqrt(linearh))

fig, ax = plt.subplots()

ax.set_xscale('log')
ax.set_yscale('log')

ax.set_xlabel('f [kHz]')
ax.set_ylabel('h$_{21e}$ [A/A]')

ax.scatter(f, h21e, marker='.', color='k')

linearf_ext = list(linearf) + [ax.get_xlim()[1]]
logA = np.log(linearf_ext)
y_fit = np.exp(m * logA + c)
ymin, ymax = ax.get_ylim()
ax.plot(linearf_ext, y_fit, color='r', linestyle='-')
ax.set_ylim(ymin, ymax)
plt.tight_layout()
plt.show()

extended linear regression

相关问题 更多 >

    热门问题