简体   繁体   English

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

[英]How do I extend a linear regression plot in matplotlib

I've encountered a problem trying to fit a straight to linear part of my plot.我在尝试将 plot 的直线部分拟合到线性部分时遇到了问题。 To finish my plot I have to extend the red line as if it were a straight, so that it's intersection with at least x axis can be observed.为了完成我的 plot,我必须将红线延伸为直线,以便至少可以观察到它与 x 轴的交点。

My code is:我的代码是:

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()

and my plot looks like this:我的 plot 看起来像这样:

绘图图像

You could add the maximum of the x-axis and append it at the end of linearf .您可以将 x 轴的最大值和 append 添加到linearf的末尾。 Then calculate the curve, and draw it.然后计算曲线,并绘制它。 The old y-limits need to be saved and reset, to prevent matplotlib to automatically extend these limits.需要保存并重置旧的 y 限制,以防止 matplotlib 自动扩展这些限制。 Note that the x-lims only can be extracted after plotting the scatter plot.请注意,只能在绘制散点 plot 后提取 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()

扩展线性回归

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM