Python數據處理——繪制函數圖形以及數據擬合


1.多項式擬合

對散點進行多項式擬合並打印出擬合函數以及擬合后的圖形
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(1,17,1) #生成散點列表作為x的值
y=np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60]) #給定y的散點值
#用3次多項式擬合
z1=np.polyfit(x,y,3)
p1=np.poly1d(z1)
print(p1) #打印擬合的多項式
yvals=p1(x) #擬合后的y值
plot1=plt.plot(x,y,'r*',label='original values')
plot2=plt.plot(x,yvals,'b',label='polyfit values')
plt.xlabel('X ')
plt.ylabel('Y')
# 'best' : 0, (only implemented for axes legends)(自適應方式)
# 'upper right' : 1,
# 'upper left' : 2,
# 'lower left' : 3,
# 'lower right' : 4,
# 'right' : 5,
# 'center left' : 6,
# 'center right' : 7,
# 'lower center' : 8,
# 'upper center' : 9,
# 'center' : 10,
plt.legend(loc=3) #設置圖示的位置
plt.title('polyfitting') #設置標題
plt.show() #顯示圖片
plt.savefig('p1.png')

 

 

2.指定函數擬合

#使用非線性最小二乘法擬合
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
#用指數形式來擬合
x = np.arange(1, 17, 1)
y = np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60])
def func(x,a,b):
    return a*np.exp(b/x)
popt, pcov = curve_fit(func, x, y)
a=popt[0]#popt里面是擬合系數,讀者可以自己help其用法
b=popt[1]
yvals=func(x,a,b)
plot1=plt.plot(x, y, '*',label='original values')
plot2=plt.plot(x, yvals, 'r',label='curve_fit values')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend(loc=4)#指定legend的位置,讀者可以自己help它的用法
plt.title('curve_fit')
plt.show()
plt.savefig('p2.png')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM