1. 程式人生 > >matplotlib繪製平滑的曲線

matplotlib繪製平滑的曲線

matplotlib繪製平滑的曲線有2種常用的方法

1.曲線擬合

使用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()

1
使用scipy.interpolate.spline擬合曲線:

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 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.間隔畫曲線

當matplotlib畫圖的橫座標為時間時,使用scipy.interpolate.spline擬合曲線就會遇到麻煩,我們可以採用間隔點畫圖。
原先的圖:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10,0.2)
y = np.random.rand(len(x))
plt.plot(x,y, marker="o")
plt.show()

3
間隔點畫圖:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10,0.2)
y = np.random.rand(len(x))
plt.plot(x[::4],y[::4], marker="o")
plt.show()

4
參考資料:
Plot smooth line with PyPlot
matplotlib中的平滑線圖具有較少的資料點