You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Matplotlib绘图代码 将6张带竖线的子图转为平滑曲线

代码优化与平滑实现方案

核心问题说明

你看到的异常竖线是原始时序数据存在瞬时跳变、采样间隔不均导致的折线突兀连接,通过make_interp_spline三次样条插值拟合趋势即可得到平滑曲线。

优化后的完整代码

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import make_interp_spline

# 通用平滑函数:输入原始x、y,返回平滑后的采样点
def smooth_curve(x, y, sample_num=300, k=3):
    # 先确保x单调递增(时序数据必须满足)
    x_sorted = np.sort(x)
    y_sorted = y[np.argsort(x)]
    # 生成更密集的采样点
    x_smooth = np.linspace(x_sorted.min(), x_sorted.max(), sample_num)
    # 三次样条拟合
    spl = make_interp_spline(x_sorted, y_sorted, k=k)
    y_smooth = spl(x_smooth)
    return x_smooth, y_smooth

# 数据预处理
plt.rcParams["figure.figsize"] = (12,3)
df=pd.read_csv("plot_data00.txt")
df=df[df['DOY'].between(184,187)]
df["HR"] = df["HR"]/24
df["DOY"] = df["DOY"]+ df["HR"]
# 按时间排序,避免插值异常
df = df.sort_values("DOY").reset_index(drop=True)

# 创建画布
fig=plt.figure(figsize=(20,17))

# 子图1:By
plt1=fig.add_subplot(611)
x_smooth, y_smooth = smooth_curve(df["DOY"], df["By"])
plt1.plot(x_smooth, y_smooth)
# 可选:添加原始散点对照真实值
# plt1.scatter(df["DOY"], df["By"], s=3, alpha=0.4, color="gray")
plt1.set_ylabel("By",size=16)
plt1.set_title("3-6 July 2003",size=20)
plt1.get_yaxis().set_label_coords(-0.05,0.5)

# 子图2:Bz
plt2=fig.add_subplot(612)
x_smooth, y_smooth = smooth_curve(df["DOY"], df["Bz"])
plt2.plot(x_smooth, y_smooth)
plt2.set_ylabel("Bz",size=16)
plt2.get_yaxis().set_label_coords(-0.05,0.5)

# 子图3:Vsw
plt3=fig.add_subplot(613)
x_smooth, y_smooth = smooth_curve(df["DOY"], df["Vsw"])
plt3.plot(x_smooth, y_smooth)
plt3.set_ylabel("Vsw",size=16)
plt3.get_yaxis().set_label_coords(-0.05,0.5)

# 子图4:Nsw
plt4=fig.add_subplot(614)
x_smooth, y_smooth = smooth_curve(df["DOY"], df["Nsw"])
plt4.plot(x_smooth, y_smooth)
plt4.set_ylabel("Nsw",size=16)
plt4.get_yaxis().set_label_coords(-0.05,0.5)

# 子图5:MRR
plt5=fig.add_subplot(615)
x_smooth, y_smooth = smooth_curve(df["DOY"], df["reconnection_rate"])
plt5.plot(x_smooth, y_smooth)
plt5.set_ylabel("MRR",size=16)
plt5.get_yaxis().set_label_coords(-0.05,0.5)

# 子图6:MD
plt6=fig.add_subplot(616)
x_smooth, y_smooth = smooth_curve(df["DOY"], df["magnetopause_distance"])
plt6.plot(x_smooth, y_smooth)
plt6.set_ylabel("MD",size=16)
plt6.set_xlabel("Day of Year",size=16)
plt6.get_yaxis().set_label_coords(-0.05,0.5)

plt.savefig('myplot03.jpg', format='jpeg',dpi=None, edgecolor='g', transparent=True, bbox_inches='tight')

参数调整说明

  • 调整smooth_curve函数的sample_num参数:数值越小平滑程度越高,数值越大越贴近原始数据波动
  • 调整k参数:默认为3(三次样条),改为2平滑度更高,改为4更贴近原始值
  • 如果数据噪声过大,可先做滑动平均预处理再插值,示例:df["By"] = df["By"].rolling(5, center=True).mean().dropna(),窗口大小可根据数据采样密度调整

内容的提问来源于stack exchange,提问作者Prater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:48:03