Matplotlib 绘制平滑曲线
文章出处:https://www.delftstack.com/zh/howto/matplotlib/matplotlib-plot-smooth-curve/
文章目录引言一、使用`scipy.ndimage.gaussian_filter1d()`高斯核类绘制平滑曲线二、使用`scipy.interpolate.make_interp_spline()`样条插值类绘制平滑曲线三、使用`scipy.interpolate.interp1d`插值类绘制平滑曲线引言使用scipy.ndimage.gaussian_filter1d()高斯核类绘制平滑曲线使用scipy.interpolate.make_interp_spline()样条插值类绘制平滑曲线使用scipy.interpolate.interp1d插值类绘制平滑曲线本教程解释了如何使用Scipy和Matplotlib包中的模块从给定坐标绘制一条平滑的曲线。
默认情况下,matplotlib.pyplot.plot()函数是通过将数据中相邻的两个点用直线连接起来产生曲线,因此matplotlib.pyplot.plot()函数对于少量的数据点并不能产生平滑曲线。
为了绘制一条平滑曲线,我们首先要对曲线拟合一条曲线,并利用曲线找到x值对应的y值,并以无限小的空隙分开。最后,我们通过绘制那些间隙很小的点,得到一条平滑曲线
一、使用scipy.ndimage.gaussian_filter1d()高斯核类绘制平滑曲线importnumpyasnpimportmatplotlib.pyplotaspltfromscipy.ndimageimportgaussian_filter1dx=np.array([1,2,3,4,5,6,7])y=np.array([100,50,25,12.5,6.25,3.125,1.5625])y_smoothed=gaussian_filter1d(y,sigma=5)plt.plot(x,y_smoothed)plt.title("SplineCurveUsingtheGaussianSmoothing")plt.xlabel("X")plt.ylabel("Y")plt.show()输出
sigma参数代表高斯核的标准差,增加sigma的值会得到更平滑的曲线。
二、使用scipy.interpolate.make_interp_spline()样条插值类绘制平滑曲线importnumpyasnpfromscipy.interpolateimportmake_interp_splineimportmatplotlib.pyplotaspltx=np.array([1,2,3,4,5,6,7])y=np.array([100,50,25,12.5,6.25,3.125,1.5625])model=make_interp_spline(x,y)xs=np.linspace(1,7,500)ys=model(xs)plt.plot(xs,ys)plt.title("SmoothSplineCurve")plt.xlabel("X")plt.ylabel("Y")plt.show()输出它通过使用scipy.interpolate.make_interp_spline()首先确定花键曲线的系数,绘制出一条平滑的花键曲线。我们用给定的数据来估计花样曲线的系数,然后用系数来确定间隔紧密的x值的y值,使曲线平滑。绘制曲线需要沿X轴1到7之间间隔相等的500。
三、使用scipy.interpolate.interp1d插值类绘制平滑曲线importnumpyasnpfromscipy.interpolateimportinterp1dimportmatplotlib.pyplotaspltx=np.array([1,2,3,4,5,6,7])y=np.array([100,50,25,12.5,6.25,3.125,1.5625])cubic_interploation_model=interp1d(x,y,kind="cubic")xs=np.linspace(1,7,500)ys=cubic_interploation_model(xs)plt.plot(xs,ys)plt.title("SplineCurveUsingCubicInterpolation")plt.xlabel("X")plt.ylabel("Y")plt.show()输出
它使用scipy.interpolate.interp1d类生成一条立方插值曲线,然后我们使用这条曲线来确定间距紧密的x值,从而得到一条平滑的曲线。绘制曲线时,需要在X轴上1和7之间取间隔相等的500个点。