简体   繁体   中英

Plotting graph using scipy.optimize.curve_fit

I am having trouble in understanding the optimize.curve_fit function. My fitting function is a power law. But I don't know exactly what should be the second value in the plot command? First we have to call function ff(L,v) it will return us fitting line but we are not calling this function. How this command is working I want to know that.

x=Ls
y=Tc
#fitting function
def ff(L,v):
    return L**(-1/v)
pfit,perr=optimize.curve_fit(ff,x,y)
plt.plot(x,...)

The plot command plots x vs y values, so you have to calculate the corresponding y-values according to your defined function ff . Since pfit is returned as an array, you have to unpack the values when you call your fit function ff . If you know, that you have two coefficients, you could of course simply extract them like v, k = pfit and calculate the y-values with ff(x, v, k) . But what if you change the fit function later on to L**(-1/v) * k + a ? Then you would have to rewrite your code. An easier way is to leave it to Python to unpack your coefficients with *pfit :

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

#define some sample data
x = np.arange(1, 6)
y = np.asarray([100, 37, 18, 3, 1])

#fitting function with more than one parameter to fit
def ff(L, v, k):
    return L**(-1/v) * k

pfit, perr = curve_fit(ff,x,y)
print(pfit)

#plot original data
plt.plot(x, y, "ro", label = "data")
#calculate y-values
y_fit = ff(x, *pfit)
#plot fitted curve
plt.plot(x, y_fit, "b", label = "fit")
plt.legend()
plt.show()

This is of course less than impressive, the fitted curve doesn't look smooth at all: 在此处输入图片说明

To overcome this, we might want to create an x-value range with a better resolution and plot this one instead of the original x-value data:

x_fit = np.linspace(np.min(x), np.max(x), 1000)
plt.plot(x_fit, ff(x_fit, *pfit), "b", label = "fit")

Much better now:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM