How to Fit Data with Python: From Scatter Plot to Exponential Curve
This article explains the concept of data (curve) fitting, demonstrates how to plot raw data points with Matplotlib, and shows step‑by‑step how to use SciPy's curve_fit to derive an exponential model that matches the given dataset.
Data fitting , also known as curve fitting, is a method of representing discrete data with a continuous mathematical function. In science and engineering, sampled or experimental data are often fitted to a curve to model the underlying relationship.
Given the data
<code>x = [1, 2, 3, 4, 5, 6]
y = [300, 500, 800, 1300, 3000, 5000]
</code>We first visualize the points using Matplotlib:
<code>import matplotlib.pyplot as plt
%matplotlib inline
x = [1,2,3,4,5,6]
y = [300,500,800,1300,3000,5000]
plt.scatter(x, y)
</code>To fit an exponential relationship we define a model function and use scipy.optimize.curve_fit to estimate its parameters:
<code># Define the function (x is the independent variable)
import numpy as np
def func(x, a, k):
return a * np.e**(k * x)
# Perform the fitting
from scipy.optimize import curve_fit
(a, k), _ = curve_fit(func, x, y)
</code>The fitting yields the coefficients:
a = 137.86824487839056, k = 0.6003825942342587
Thus the final fitted function is f(x) = 137.86824487839056 * e^(0.6003825942342587 * x) . The fit quality is illustrated below:
Reference: Baidu Baike – Data Fitting
Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.