如何平滑Matplotlib绘制的实验数据折线图曲线
如何用Matplotlib平滑折线图曲线?
针对你遇到的Matplotlib绘制曲线不够平滑的问题,这里有几种实用的平滑处理方案,你可以根据数据特性和需求选择:
方法1:滑动窗口平均(Moving Average)
这是最简单易上手的平滑方式,通过计算相邻N个数据点的平均值来过滤噪声,适合数据噪声不算特别大的场景。你可以直接用pandas的rolling()方法快速实现:
# 读取数据后,添加滑动窗口平滑步骤 window_size = 5 # 窗口大小可根据噪声程度调整,噪声大就调大(比如10) df['y1_smoothed'] = df['y1_values'].rolling(window=window_size, center=True).mean() df['y2_smoothed'] = df['y2_values'].rolling(window=window_size, center=True).mean() # 替换原绘图代码,绘制平滑后的曲线 plt.plot('x_values', 'y2_smoothed', data=df, color='blue', linewidth=1.5, label="hello (smoothed)") plt.plot('x_values', 'y1_smoothed', data=df, color='red', linewidth=1.5, label="hi (smoothed)")
center=True参数让窗口居中计算,避免平滑后的曲线出现偏移;如果数据中有缺失值,记得先用df.dropna()或者df.fillna()处理后再做平滑。
方法2:多项式拟合(Polynomial Fitting)
如果你的数据有明显的整体趋势,多项式拟合能生成贴合趋势的平滑曲线。用numpy的polyfit()和poly1d()就能实现:
# 选择多项式阶数(建议3-5阶,阶数过高会过度拟合噪声) degree = 3 # 对第一条曲线进行拟合 z1 = np.polyfit(df['x_values'], df['y1_values'], degree) p1 = np.poly1d(z1) # 生成更密集的x点,让曲线更顺滑 x_smooth = np.linspace(df['x_values'].min(), df['x_values'].max(), 500) y1_smoothed = p1(x_smooth) # 对第二条曲线进行拟合 z2 = np.polyfit(df['x_values'], df['y2_values'], degree) p2 = np.poly1d(z2) y2_smoothed = p2(x_smooth) # 绘制平滑后的曲线 plt.plot(x_smooth, y2_smoothed, color='blue', linewidth=1.5, label="hello (smoothed)") plt.plot(x_smooth, y1_smoothed, color='red', linewidth=1.5, label="hi (smoothed)")
注意不要选太高的阶数,不然曲线会过度贴合原始数据的噪声,失去平滑的意义。
方法3:样条插值(Spline Interpolation)
样条插值能生成更自然流畅的平滑曲线,适合非线性趋势的数据,需要用到scipy库(如果没装的话先运行pip install scipy):
from scipy.interpolate import make_interp_spline # 生成更密集的x点 x_smooth = np.linspace(df['x_values'].min(), df['x_values'].max(), 500) # 对第一条曲线做三次样条插值(k=3是最常用的,平衡平滑度和贴合度) spl1 = make_interp_spline(df['x_values'], df['y1_values'], k=3) y1_smoothed = spl1(x_smooth) # 对第二条曲线做三次样条插值 spl2 = make_interp_spline(df['x_values'], df['y2_values'], k=3) y2_smoothed = spl2(x_smooth) # 绘制平滑曲线 plt.plot(x_smooth, y2_smoothed, color='blue', linewidth=1.5, label="hello (smoothed)") plt.plot(x_smooth, y1_smoothed, color='red', linewidth=1.5, label="hi (smoothed)")
如果想要曲线更贴合原始数据,可以降低k值(比如k=2);反之想要更平滑,可适当调高k值(但不建议超过5)。
小贴士
- 平滑处理本质是牺牲部分原始数据细节换取可读性,所以要根据你的需求调整平滑程度,避免过度平滑导致趋势失真。
- 如果你想保留原始曲线作为参考,可以同时绘制原始曲线(用更细的线或者浅色)和平滑曲线。
内容的提问来源于stack exchange,提问作者Khawar Islam
相关产品推荐
相关产品推荐

