#Headerimport numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Define a function(here a exponential function is used)deffunc(x, a, b, c):return a * np.exp(b * x)+ c
fo =open("data.txt",'r')
xdata =list()
ydata =list()
entry = fo.readline()#start_year = 1982
offset =0while entry:
offset +=1
lt = entry.split('\t')
data = lt[1]
data = data.rstrip('\n')#data format 1982\t203\n
xdata.append(offset)
ydata.append(int(data))
entry = fo.readline()
xdata = np.array(xdata)
ydata = np.array(ydata)
plt.plot(xdata, ydata,'bo', label='data')#mark the scatter#Fit for the parameters a, b, c of the function func:
popt, pcov = curve_fit(func, xdata, ydata)
popt #output: array([ 2.55423706, 1.35190947, 0.47450618])
xrge =list()for i inrange(2050-1982):
xrge.append(i)#draw the curve until 2050
xrge = np.array(xrge)
plt.plot(xrge, func(xrge,*popt),'r-',
label='fit: a=%5.3f, b=%5.3f, c=%5.3f'%tuple(popt))#Labels
plt.title("Exponential Function Fitting")#fc-list :lang=zh-cn Ubuntu命令行查看已安装字体
zhfont = mpl.font_manager.FontProperties(fname='/usr/share/fonts/opentype/noto/NotoSerifCJK-Bold.ttc')
plt.xlabel('年份', fontproperties=zhfont)
plt.ylabel('average GDP')
plt.legend()
leg = plt.legend()# remove the frame of Legend, personal choice
leg.get_frame().set_linewidth(0.0)# remove the frame of Legend, personal choice#Export figure
plt.savefig('fit1.jpg',format='jpg', dpi=1000, facecolor='w', edgecolor='k')
使用numpy拟合预测人均GDP趋势文章目录实现代码结果图例数据[2]Tips实现代码#Headerimport numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit#Define a function(here a exponential function is used)def func(x, a, b, c): return a