[英]How do I extend a linear regression plot in matplotlib
我在嘗試將 plot 的直線部分擬合到線性部分時遇到了問題。 為了完成我的 plot,我必須將紅線延伸為直線,以便至少可以觀察到它與 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 看起來像這樣:
您可以將 x 軸的最大值和 append 添加到linearf
的末尾。 然后計算曲線,並繪制它。 需要保存並重置舊的 y 限制,以防止 matplotlib 自動擴展這些限制。 請注意,只能在繪制散點 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.