如何使用 curve_fit 和线性函数绘制散点图的下边界?

How to plot lower boundary with a scatter plot with curve_fit and a linear line function?

我使用以下代码绘制散点图。我一直在尝试为它绘制下边界。我尝试关注另一个问题,但无法为我的 objective 函数和数据复制它。代码如下:

from numpy import arange
import pandas as pd
from pandas import read_csv
from scipy.optimize import curve_fit
from matplotlib import pyplot
 

def objective(x, a, b):
    return a * x + b
 
events = pd.read_excel('values.xlsx')
x = events.loc[:, 'Value']
y = events.loc[:, 'Frame']

popt, _ = curve_fit(objective, x, y)


a, b = popt
pyplot.scatter(x, y)


x_line = arange(min(x), max(x), 1)
y_line = objective(x_line, a, b)
pyplot.plot(x_line, y_line, '--', color='purple')
xmin, xmax = pyplot.xlim() # the limits of the x-axis for drawing the line
ymin, ymax = pyplot.ylim()

pos_min = np.argmin(x)
pos_max = np.argmax(x)

alpha_min = x[pos_min] 
alpha_max = x[pos_max] 

pyplot.show()

我想绘制像 这样的点的下边界。

因为你有一个线性函数,你的上限和下限将具有相同的斜率 a 但不同的 b 值。因此,我们计算所有点并选择最低和最高:

import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot     

def objective(x, a, b):
    return a * x + b
 
#sample data
rng = np.random.default_rng(123)
x = np.linspace(2, 10, 150)
y = objective(x, -2, 3)
y += 5 * rng.random(len(x))

popt, _ = curve_fit(objective, x, y) 
a, b = popt
pyplot.scatter(x, y, label="raw data")

x_line = np.asarray([np.min(x), np.max(x)])
y_line = objective(x_line, a, b)
pyplot.plot(x_line, y_line, '--', color='purple', label=f"y={a:.2f}x+{b:.2f}")

b_values = y - a * x

pyplot.plot(x_line, objective(x_line, a, np.min(b_values)), '--', color='red', label="lower bound")
pyplot.plot(x_line, objective(x_line, a, np.max(b_values)), '--', color='orange', label="upper bound")

pyplot.legend()
pyplot.show()

示例输出: