September 11, 2024

Curve Fitting in Python

Curve fitting is a process of finding a curve that best fits a series of data points. In Python, curve fitting can be performed using various libraries, with scipy being one of the most popular ones for this purpose. The scipy.optimize.curve_fit function allows you to fit a curve to your data by defining a mathematical function and finding the optimal parameters that minimize the difference between the data points and the curve.

Using scipy.optimize.curve_fit

The curve_fit function from the scipy.optimize module is used to fit a curve to data. You need to define the function that describes the curve, provide the data points, and the function will return the optimal parameters that best fit the data.

Example: Fitting a Linear Curve

In this example, we’ll fit a straight line to a set of data points. The equation of a straight line is y = mx + c, where m is the slope and c is the y-intercept.

Step-by-Step Implementation:

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

# Define the linear function to fit
def linear_function(x, m, c):
    return m * x + c

# Generate synthetic data points (for demonstration)
x_data = np.array([0, 1, 2, 3, 4, 5, 6])
y_data = np.array([0.5, 2.5, 2.0, 3.8, 4.2, 5.1, 6.5])

# Perform the curve fitting
params, covariance = curve_fit(linear_function, x_data, y_data)

# Extract the optimal parameters (slope and intercept)
slope, intercept = params

# Generate y values using the fitted parameters
fitted_y_data = linear_function(x_data, slope, intercept)

# Plot the original data points and the fitted line
plt.scatter(x_data, y_data, label="Data Points", color="red")
plt.plot(x_data, fitted_y_data, label="Fitted Line", color="blue")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.title(f"Fitted Line: y = {slope:.2f}x + {intercept:.2f}")
plt.show()
    

Output:

The output will be a plot showing the original data points (in red) and the fitted line (in blue). The equation of the fitted line will be displayed in the plot title.

Explanation

  • Defining the Function: The first step is to define the mathematical function that describes the curve you want to fit. In this example, we define a linear function y = mx + c.
  • Generating Data: We generate some synthetic data points for demonstration purposes. In practice, you would use your actual data.
  • Curve Fitting: We use curve_fit to find the optimal values of the parameters m and c that best fit the data.
  • Plotting: We plot the original data points and the fitted line to visualize the fit.

Fitting Non-Linear Curves

Curve fitting is not limited to linear functions. You can fit non-linear functions by defining the appropriate mathematical function and using curve_fit. Below is an example of fitting a quadratic curve.

Example: Fitting a Quadratic Curve

# Define the quadratic function to fit
def quadratic_function(x, a, b, c):
    return a * x**2 + b * x + c

# Generate synthetic data points (for demonstration)
x_data = np.array([0, 1, 2, 3, 4, 5, 6])
y_data = np.array([1.2, 2.8, 4.5, 8.4, 12.5, 18.3, 25.1])

# Perform the curve fitting
params, covariance = curve_fit(quadratic_function, x_data, y_data)

# Extract the optimal parameters
a, b, c = params

# Generate y values using the fitted parameters
fitted_y_data = quadratic_function(x_data, a, b, c)

# Plot the original data points and the fitted curve
plt.scatter(x_data, y_data, label="Data Points", color="red")
plt.plot(x_data, fitted_y_data, label="Fitted Quadratic Curve", color="green")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.title(f"Fitted Quadratic Curve: y = {a:.2f}x^2 + {b:.2f}x + {c:.2f}")
plt.show()
    

Output:

The output will be a plot showing the original data points and the fitted quadratic curve, with the equation displayed in the plot title.

Conclusion

Curve fitting is a valuable tool for data analysis and modeling, allowing you to find the mathematical function that best describes your data. Python’s scipy.optimize.curve_fit function makes it easy to perform both linear and non-linear curve fitting. By understanding how to use this function, you can apply curve fitting to a wide range of problems in science, engineering, and other fields.