簡體   English   中英

Scipy curve_fit:如何繪制擬合曲線超出數據點?

[英]Scipy curve_fit: how to plot the fitted curve beyond the data points?

我有許多數據點,並且使用了Scipy curve_fit將曲線擬合到該數據集。 現在,我想繪制超出數據點范圍的擬合,而我不知道該怎么做。

這是一個基於指數擬合的簡單示例:

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

def exponential_fit(x, a, b, c):
    return a*np.exp(-b*x) + c

x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([30, 50, 80, 160, 300, 580])
fitting_parameters, covariance = curve_fit(exponential_fit, x, y)
a, b, c = fitting_parameters

plt.plot(x, y, 'o', label='data')
plt.plot(x, exponential_fit(x, *fitting_parameters), '-', label='Fit')

plt.axis([0, 8, 0, 2000])
plt.legend()
plt.show()

這將返回以下圖:

在此處輸入圖片說明

現在如何擴展擬合的(橙色)曲線,使其達到x = 8? 請注意,我不想創建其他數據點,而只是想擴展擬合曲線的范圍。

提前謝謝了。

您必須為x定義一個額外的數據范圍,以將其擴展到數據點給定的數據范圍之外。 您甚至可以改善表示並為fit函數計算更多x值:

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

def exponential_fit(x, a, b, c):
    return a*np.exp(-b*x) + c

x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([30, 50, 80, 160, 300, 580])
fitting_parameters, covariance = curve_fit(exponential_fit, x, y)
a, b, c = fitting_parameters

x_min = -4  
x_max = 8                                #min/max values for x axis
x_fit = np.linspace(x_min, x_max, 100)   #range of x values used for the fit function
plt.plot(x, y, 'o', label='data')
plt.plot(x_fit, exponential_fit(x_fit, *fitting_parameters), '-', label='Fit')

plt.axis([x_min, x_max, 0, 2000])
plt.legend()
plt.show()

為了增加靈活性,我介紹了x_min, x_max ,因為相同的值用於計算擬合函數使用的x值的范圍並縮放圖的軸。 numpy.linspace在開始值和停止值之間創建均勻間隔的樣本,用作x值以計算fit函數中的相應y值。

x范圍是0到5。如果希望曲線上升到8( 或上升到11 ),則需要提供一個數組,其范圍在11到...對不起8。

x_new = np.linspace(0,11)
plt.plot(x_new, exponential_fit(x_new, *fitting_parameters), '-', label='Fit')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM