我在使用curve_fit函数时遇到一些麻烦

时间:2019-10-17 05:47:37

标签: python-3.x

我想用curve_fit函数拟合散点图。但是尽管我按照教程中的说明编写了代码,但还是没用,有人可以帮我检查一下代码吗?

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

rcParams['axes.unicode_minus']=False
myfont = FontProperties(fname='/Library/Fonts/Songti.ttc',size=15)

ydata=[78,78,77.9,74,8,70.1,65.8,58.2,40,5.0,14.0,30,60,69,74,74.2,78,78]
xdata = [257.6695,257.6695,257.6695,307.7231,316.009,309.4141,310.936,312.627,314.4871,316.3472,    317.0236,317.7,319.391,321.082,322.9421,    324.464,    341.7122,426.7695]
plt.plot(xdata,ydata,'*')
plt.xlabel('磁感应强度B(mT)',fontproperties=myfont)
plt.ylabel('检波电流(μA)', fontproperties=myfont)


def func(x,amp,cen,wid):
    return amp*np.exp(-(x-cen)**2/wid)

popt,pcov = curve_fit(func,xdata,ydata)
print(popt)
amp = popt[0]
cen = popt[1]
wid = popt[2]
residuals = ydata-func(xdata,amp,cen,wid)
fres = sum(residuals**2)
print(fres)

xaxis = np.linspace(250,450,100)
curve_y = func(xaxis,amp,cen,wid)
plt.plot(xaxis,curve_y)

1 个答案:

答案 0 :(得分:0)

对于maplotlib.pyplot,您需要明确声明要“显示”绘图以使其显示。

plt.plot(x, y)将创建图形的准系统,但仍然可以做出许多更改:添加其他图形或子图,向图形添加其他数据集以进行比较或更改颜色!

直到您明确地说“在代码中显示此刻的绘图”,然后什么都不会发生。尝试在代码末尾添加以下内容:

plt.show()