基本思想
其實就是找到原來散點圖x和y的對應關係,然後通過大量的採樣點來擬合來近似曲線。
1.法1
這個方法網上有很多blog,但是問題是它使用的函數在新版的matplotlib裏已經沒了(可能換名字了,我也沒查)。不過還是轉載過來一下。轉自:原blog
使用scipy庫可以擬合曲線.
沒擬合的圖:
import matplotlib.pyplot as plt
import numpy as np
T = np.array([6, 7, 8, 9, 10, 11, 12])
power = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00])
plt.plot(T,power)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
T = np.array([6, 7, 8, 9, 10, 11, 12])
power = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00])
from scipy.interpolate import spline # 如果你的matplotlib版本較新,這個會報錯
xnew = np.linspace(T.min(),T.max(),300) #300 represents number of points to make between T.min and T.max
power_smooth = spline(T,power,xnew)
plt.plot(xnew,power_smooth)
plt.show()
2.法2
使用:scipy.interpolate.interp1d
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
x = np.array([6, 7, 8, 9, 10, 11, 12])
y = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00])
xnew = np.linspace(x.min(),x.max(),300)
func = interp1d(x,y,kind='cubic')
ynew = func(xnew)
plt.plot(xnew,ynew) # 此時即爲平滑曲線