Python Matplotlib-如何通过误差条绘制最小和最大梯度线?

Python Matplotlib-如何通过误差条绘制最小和最大梯度线?,python,matplotlib,plot,graph,Python,Matplotlib,Plot,Graph,我的代码: import matplotlib import numpy as np import matplotlib.pyplot as plt from lmfit import Model def bestfit(x, m, c): return m * x + c x = [2.8672E-02, 2.2199E-02, 1.8180E-02, 1.5410E-02, 1.3325E-02] y = [8.64622E-03, 7.07473E-03, 6.13109E-0

我的代码:

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model

def bestfit(x, m, c):
    return m * x + c

x = [2.8672E-02, 2.2199E-02, 1.8180E-02, 1.5410E-02, 1.3325E-02]
y = [8.64622E-03, 7.07473E-03, 6.13109E-03, 5.46607E-03, 4.90341E-03]
xerror =[8.2209E-07, 4.9280E-07, 3.3052E-07, 2.3748E-07, 1.7756E-07]
yerror = [1.62083E-04, 1.45726E-04, 1.38127E-04, 1.26587E-04, 1.22042E-04]

mod = Model(bestfit)
params = mod.make_params(m = 0.2421, c = 0.0017)
result = mod.fit(y, params, x = x)
print(result.fit_report())
print(1 - result.residual.var() / np.var(y))

matplotlib.rcParams['font.serif'] = "Times New Roman"
matplotlib.rcParams['font.family'] = "serif"
plt.plot(x, y, 'bo', markersize = 1.5)
plt.plot(x, result.best_fit, color = 'red', linewidth = 0.5)
plt.xlabel(r'Inverse Mass $g^{-1}$')
plt.ylabel('Damping Coefficient $s^{-1}$')


plt.errorbar(x, y, xerror, yerror)
plt.show()
我希望创建最小和最大梯度线,以及它们的方程,如下所示:

我可以在Excel中完成,但这需要手动输入4个极端数据点


如何自动执行此操作?

我不清楚其他程序显示的曲线。看起来它可能只是画了一条穿过这些点的线

  (x[0], y[0]-yerror[0]), (x[-1], y[-1]+yerror[-1])
  (x[0], y[0]+yerror[0]), (x[-1], y[-1]-yerror[-1])
使用matplotlib绘图应该很容易。但这对我来说并不是特别有意义

另一方面,如果您想在绘图中包含拟合结果不确定性的一些度量,那么有几个选项。首先,您可以使用从最佳拟合值中获取的参数值以及这些值中的不确定性来评估模型。例如,您可以这样做(一旦有了
result
):

然后画出其中一些

一个更简单且可能信息更丰富的绘图是使用
ModelResult
eval\u不确定性
方法。看见 一个简单的用法是:

dely = result.eval_uncertainty()
plt.fill_between(x, result.best_fit-dely, result.best_fit+dely, color="#ABABAB")
此外,由于
y
中存在不确定性,因此可以在拟合本身中使用这些不确定性。要使用
lmfit.Model
执行此操作,您需要将
1.0/yerror
作为
weight
传递给
fit
方法:

result = mod.fit(y, params, x=x, weights=1.0/np.array(yerror))
(注意:数据和不确定性应该是numpy数组,而不是列表)。我认为对于您的数据(不确定性大小相似),它不会对最佳拟合值和不确定性产生太大影响,但会对报告的统计数据(如卡方检验)产生影响

最后,对于一个简单的线性模型(即,一个参数是线性的模型,就像这个),您实际上不需要使用像
lmfit.model
这样的迭代方法,但可以使用线性回归方法

result = mod.fit(y, params, x=x, weights=1.0/np.array(yerror))