Skip to content Skip to sidebar Skip to footer

Trouble With Curve Fitting - Matplotlib

I am trying to plot a sin function to a data set. I found a tutorial online using scipy.optimize, but it seems not to work even though I copied the code exactly. At the top: def fu

Solution 1:

of course it does not plot anything, curve_fit does not plot.

Look in the documentation, the return values of curve_fit are an array with the estimated parameters and a 2d array with the estimated covariance matrix. You have to plot the fit-function with the estimated parameters yourself.

I also would suggest to fit a*sin(bx +c) +d as then b and c are not correlated.

this works:

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

x_data = np.linspace(0, 2*np.pi, 30)
y_data = np.sin(x_data) + normal(0, 0.2, 30)


deffunc(x, a, b, c, d):
    return a * np.sin(b*x + c) + d

parameter, covariance_matrix = curve_fit(func, x_data, y_data)

x = np.linspace(min(x_data), max(x_data), 1000)
plt.plot(x_data, y_data, 'rx', label='data')
plt.plot(x, func(x, *parameter), 'b-', label='fit')   # the star is to unpack the parameter array
plt.show()

this is the result:

plot result

Solution 2:

I have an example code with data in the form a sine curve and a user defined function that fits the data.

Here is the code:

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

xdata = np.array([2.65, 2.80, 2.96, 3.80, 3.90, 4.60, 4.80, 4.90, 5.65, 5.92])
ydata = np.sin(xdata)

deffunc(x,p1,p2,p3): # HERE WE DEFINE A SIN FUNCTION THAT WE THINK WILL FOLLOW THE DATA DISTRIBUTIONreturn p1*np.sin(x*p2+p3)

# Here you give the initial parameters for p0 which Python then iterates over# to find the best fit
popt, pcov = curve_fit(func,xdata,ydata,p0=(1.0,1.0,1.0)) #THESE PARAMETERS ARE USER DEFINEDprint(popt) # This contains your two best fit parameters# Performing sum of squares
p1 = popt[0]
p2 = popt[1]
p3 = popt[2]
residuals = ydata - func(xdata,p1,p2,p3)
fres = sum(residuals**2)

print(fres) #THIS IS YOUR CHI-SQUARE VALUE!

xaxis = np.linspace(1,7,100) # we can plot with xdata, but fit will not look good 
curve_y = func(xaxis,p1,p2,p3)
plt.plot(xdata,ydata,'*')
plt.plot(xaxis,curve_y,'-')
plt.show()

enter image description here

Post a Comment for "Trouble With Curve Fitting - Matplotlib"