Scipy curve_fit:如何绘制拟合曲线超出数据点? [英] Scipy curve_fit: how to plot the fitted curve beyond the data points?

查看:177
本文介绍了Scipy curve_fit:如何绘制拟合曲线超出数据点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多数据点,并且我使用了Scipy curve_fit 将曲线拟合到该数据集。我现在想绘制超出数据点范围的拟合强度 ,但我不知道该怎么做。

I have a number of data points and I used Scipy curve_fit to fit a curve to this data set. I now would like to plot the fit beyond the range of data points and I cannot find out how to do it.

这是一个基于指数拟合的简单示例:

Here is a simple example based on an exponential fitting:

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?请注意,我不想创建其他数据点,而只是想扩大拟合曲线的范围。

Now how can I extend the fitted (orange) curve so it goes up to x = 8? Please note that I do not want to create additional data points I just want to expand the range of the fitted curve.

在此先感谢您。

推荐答案

您必须为x定义一个额外的数据范围,以将其扩展到数据点给定的数据范围之外。您甚至可以改进表示形式并为fit函数计算更多x值:

You have to define an extra data range for x to extend it beyond the data range given by your data points. You can even improve the representation and calculate more x values for the fit function:

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值。

For added flexibility, I introduced x_min, x_max, because the same values are used to calculate the range for x values used by the fit function and to scale the axis for the plot. numpy.linspace creates an evenly spaced sample between start and stop value, used as x values to calculate the corresponding y values in the fit function.

这篇关于Scipy curve_fit:如何绘制拟合曲线超出数据点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆