Matplotlib实现时间序列按固定间隔拆分多图绘制
解决3分钟间隔时间序列子图为空的问题
针对你遇到的时间序列拆分后绘图为空的情况,可从以下几个方向排查并修正:
1. 确保时间索引为datetime类型
如果DataFrame索引是字符串格式,切片逻辑会直接失效,导致子数据为空。先检查并转换:
import pandas as pd import matplotlib.pyplot as plt # 转换索引为datetime类型(若当前为字符串格式) df.index = pd.to_datetime(df.index) # 验证类型:输出应为datetime64[ns] print(df.index.dtype)
2. 修正时间切片与绘图逻辑
错误的时间范围生成会导致切片无数据,以下是验证过的完整循环绘图代码:
# 生成所有连续3分钟的起始时间(避免最后一段不足3分钟) start_times = pd.date_range( start=df.index.min(), end=df.index.max() - pd.Timedelta(minutes=3), freq='3T' ) # 循环绘制每个子时间段的图 for idx, start in enumerate(start_times): end = start + pd.Timedelta(minutes=3) # 切片获取当前3分钟的子数据(pandas的.loc支持时间范围闭区间) sub_df = df.loc[start:end] # 跳过无数据的时间段 if sub_df.empty: print(f"警告:{start} 至 {end} 无数据") continue # 创建独立画布,避免子图重叠或覆盖 plt.figure(figsize=(10, 8)) # 绘制4个变量的子图 plt.subplot(4, 1, 1) plt.plot(sub_df.index, sub_df['Flow'], color='blue') plt.title(f"时间段:{start.strftime('%H:%M')} - {end.strftime('%H:%M')}") plt.ylabel('Flow') plt.subplot(4, 1, 2) plt.plot(sub_df.index, sub_df['HeartRate'], color='orange') plt.ylabel('HeartRate') plt.subplot(4, 1, 3) plt.plot(sub_df.index, sub_df['Pressure'], color='green') plt.ylabel('Pressure') plt.subplot(4, 1, 4) plt.plot(sub_df.index, sub_df['O2'], color='red') plt.ylabel('O2') plt.xlabel('Time') # 调整布局,避免标签重叠 plt.tight_layout() # 保存子图(或用plt.show()直接显示) plt.savefig(f"timeslot_subplot_{idx+1}.png") plt.close() # 关闭画布,释放内存
3. 排查常见坑点
- 时间精度不匹配:如果数据时间戳包含毫秒/微秒,切片时可通过
start.floor('min')和end.ceil('min')对齐到分钟级别,避免因精度差导致切片为空。 - 起始/结束时间错误:确保
start_times的结束时间是df.index.max() - 3分钟,避免生成超出数据范围的时间段。 - 绘图环境问题:在Jupyter Notebook中需添加
%matplotlib inline才能显示图像;脚本中需确保plt.savefig或plt.show()被调用,且每次循环创建新画布。
内容的提问来源于stack exchange,提问作者nachodonlucero
相关产品推荐
相关产品推荐

