【问题标题】:Scipy curve_fit: how to plot the fitted curve beyond the data points?Scipy curve_fit:如何在数据点之外绘制拟合曲线?
【发布时间】:2018-01-30 18:21:00
【问题描述】:

我有许多数据点,我使用 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?请注意,我不想创建额外的数据点,我只想扩大拟合曲线的范围。

提前非常感谢。

【问题讨论】:

    标签: python matplotlib scipy curve-fitting


    【解决方案1】:

    您必须为 x 定义一个额外的数据范围,以将其扩展到您的数据点给定的数据范围之外。您甚至可以改进表示并为拟合函数计算更多 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,因为相同的值用于计算 fit 函数使用的 x 值的范围并缩放绘图的轴。 numpy.linspace 在 start 和 stop 值之间创建一个均匀间隔的样本,用作 x 值来计算 fit 函数中相应的 y 值。

    【讨论】:

    • 非常感谢!注意应该是np.linspace(x_min, x_max, 100)
    • 已编辑。想知道为什么它在我的测试中仍然有效。但是 Eclipse 在脚本中插入了from numpy.core.function_base import linspace。自动化程度过高。
    【解决方案2】:

    x 的范围从 0 到 5。如果您希望曲线上升到 8 (or up to eleven),您需要提供一个范围为 11 的数组...抱歉 8。

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

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2020-06-12
      • 1970-01-01
      • 2020-05-05
      • 2021-09-25
      • 2020-07-07
      • 2013-03-17
      • 2020-07-12
      • 1970-01-01
      相关资源
      最近更新 更多