python - 如何在 matplotlib 中扩展线性回归图
问题描述
我在尝试将情节的直线部分拟合为线性部分时遇到了问题。为了完成我的情节,我必须将红线延伸为直线,以便至少可以观察到它与 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()
我的情节是这样的:
解决方案
您可以添加 x 轴的最大值并将其附加到linearf
. 然后计算曲线,并绘制它。需要保存和重置旧的 y 限制,以防止 matplotlib 自动扩展这些限制。请注意,只有在绘制散点图后才能提取 x-lims。
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()
推荐阅读
- reactjs - 开始开发 Create React App 后添加 Chakra UI
- python - 如何从队列中弹出连续值
- javascript - 平滑背景图像更改javascript
- css - 带样式组件的兄弟组合器
- r - 将多列中的不同值重新编码为因子
- html - 为什么第三列低于其他两列?
- jquery - 如何使用 ”///
"在浏览器中 - javascript - 为什么 JavaScript 中的 element.style.height 函数可能不起作用?
- windows - 进程在 Powershell Prompt 中运行,但不是作为计划任务?
- c# - 当我尝试在 if 语句中分配布尔值时出现此错误