我使用以下代碼繪制散點圖。我一直在嘗試為它繪制下邊界。我嘗試關注另一個問題,但我無法為我的目標函式和資料復制它。代碼如下:
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()
我想繪制點的下邊界,例如
.
uj5u.com熱心網友回復:
由于您具有線性函式,因此您的上限和下限將具有相同的斜率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()
樣本輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440767.html
標籤:Python 熊猫 麻木的 matplotlib scipy
