matplotlib 如何扩展线性回归图

mspsb9vt  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(94)

我遇到了一个问题,试图拟合直线到线性部分的我的图。为了完成我的图,我必须延长红线,如果它是一条直线,这样它的交叉点至少x轴可以观察到。
我的代码是:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. #data = pd.read_csv("LPPII_cw_2_1.csv")
  5. #f = data["f [kHz]"]
  6. f = (1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 500)
  7. #h21e = data["h21e [A/A]"]
  8. h21e = (218., 215., 210., 200., 189., 175., 165., 150., 140., 129., 120., 69., 30.)
  9. linearf = f[-3:]
  10. linearh = h21e[-3:]
  11. logA = np.log(linearf)
  12. logB = np.log(linearh)
  13. m, c = np.polyfit(logA, logB, 1, w=np.sqrt(linearh))
  14. y_fit = np.exp(m*logA + c)
  15. fig, ax = plt.subplots()
  16. ax.set_xscale('log')
  17. ax.set_yscale('log')
  18. ax.set_xlabel('f [kHz]')
  19. ax.set_ylabel('h$_{21e}$ [A/A]')
  20. ax.scatter(f, h21e, marker='.', color='k')
  21. ax.plot(linearf, y_fit, color='r', linestyle='-')
  22. plt.show()

我的图是这样的:

pgccezyw

pgccezyw1#

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

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. f = (1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 500)
  4. h21e = (218., 215., 210., 200., 189., 175., 165., 150., 140., 129., 120., 69., 30.)
  5. linearf = f[-3:]
  6. linearh = h21e[-3:]
  7. logA = np.log(linearf)
  8. logB = np.log(linearh)
  9. m, c = np.polyfit(logA, logB, 1, w=np.sqrt(linearh))
  10. fig, ax = plt.subplots()
  11. ax.set_xscale('log')
  12. ax.set_yscale('log')
  13. ax.set_xlabel('f [kHz]')
  14. ax.set_ylabel('h$_{21e}$ [A/A]')
  15. ax.scatter(f, h21e, marker='.', color='k')
  16. linearf_ext = list(linearf) + [ax.get_xlim()[1]]
  17. logA = np.log(linearf_ext)
  18. y_fit = np.exp(m * logA + c)
  19. ymin, ymax = ax.get_ylim()
  20. ax.plot(linearf_ext, y_fit, color='r', linestyle='-')
  21. ax.set_ylim(ymin, ymax)
  22. plt.tight_layout()
  23. plt.show()

展开查看全部

相关问题