show fit on plot python code example

Example: show fit on plot python

# Import curve fitting package from scipy
from scipy.optimize import curve_fit

# Function to calculate the exponential with constants a and b
def exponential(x, a, b):
    return a*np.exp(b*x)
  
# Generate dummy dataset
x_dummy = np.linspace(start=5, stop=15, num=50)
# Calculate y-values based on dummy x-values
y_dummy = exponential(x_dummy, 0.5, 0.5)
# Plot the noisy exponential data
ax.scatter(x_dummy, y_dummy, s=20, color='#00b3b3', label='Data')
# Fit the dummy exponential data
pars, cov = curve_fit(f=exponential, xdata=x_dummy, ydata=y_dummy, p0=[0, 0], bounds=(-np.inf, np.inf))
# Plot the fit data as an overlay on the scatter data
ax.plot(x_dummy, exponential(x_dummy, *pars), linestyle='--', linewidth=2, color='black')

Tags:

Misc Example