
本文介绍如何通过正确填充时间索引并插入 NaN 值,确保 Matplotlib 仅绘制连续有效数据段,避免跨长时间空缺(如多日缺失)后错误连线。核心方法是使用 pd.date_range 和 reindex 对齐等间隔小时级时间轴。
本文介绍如何通过正确填充时间索引并插入 nan 值,确保 matplotlib 仅绘制连续有效数据段,避免跨长时间空缺(如多日缺失)后错误连线。核心方法是使用 `pd.date_range` 和 `reindex` 对齐等间隔小时级时间轴。
在绘制长时间跨度(如整月)的温度时间序列时,若原始数据存在不规则缺失(例如连续数日无采集),而仅对单日内空缺补 NaN,Matplotlib 仍会将时间上不连续但索引相邻的有效点强行连线——因为它只认数组顺序,不理解时间语义。这导致图中出现跨越数天的“虚假连接线”,严重误导趋势解读(如你图中 10/09 周围的异常连线)。
✅ 正确做法是:构建完整、等间隔的时间基准轴,并将原始数据严格对齐到该轴上。这样,所有真实缺失时段(无论数小时或数天)都会被显式标记为 NaN,Matplotlib 自动断开绘制。
步骤详解
-
生成完整小时级时间索引
使用 pd.date_range 创建从首条记录到末条记录、频率为 'H'(每小时)的连续时间序列:import pandas as pd import matplotlib.pyplot as plt # 假设 month_year_data 已按 datetime 索引排序 full_hours = pd.date_range( start=month_year_data.index.min(), end=month_year_data.index.max(), freq='H' ) -
重索引并自动填充 NaN
reindex() 将原始 DataFrame 映射到完整时间轴,缺失位置自动填入 NaN(默认行为):month_year_data_filled = month_year_data.reindex(full_hours)
✅ 关键优势:reindex 保证时间维度严格等距,且所有空缺(包括跨日空缺)均转为 NaN,Matplotlib 绘图时自然断开。
-
绘制修正后的数据
替换原绘图代码中的 month_year_data 为 month_year_data_filled:fig, ax = plt.subplots(figsize=(20, 10)) zones = ['Far range', 'Mid range', 'Near range'] colors = ['blue', 'green', 'red'] for i, zone in enumerate(zones): # 直接使用 filled 数据 —— NaN 区域自动断开 ax.plot(month_year_data_filled.index, month_year_data_filled[zone], label=zone, color=colors[i], linestyle='-') ax.set_xlabel('Time') ax.set_ylabel('Temperature (°C)') ax.set_title(f'Temperature as a function of time by Hour - {month_name}-{year}') plt.xticks(rotation=45) ax.legend() plt.tight_layout() plt.show()
注意事项与进阶建议
索引必须为 datetime64 类型:确保 month_year_data.index 是 DatetimeIndex,否则 reindex 无法按时间对齐。可强制转换:
month_year_data.index = pd.to_datetime(month_year_data.index)
Matplotlib Linux版下载Matplotlib Linux版 3.11.1 官方下载,来自 PyPI 官方发布,适合 Python 图表绘制、数据分析、科研可视化和 Jupyter Notebook 环境安装。
避免插值干扰:reindex 默认用 method=None(即不插值),严格保留原始值 + NaN。切勿误用 interpolate() 或 fillna(),否则会伪造数据。
内存优化(大数据集):若月份数据量极大(如百万级小时点),可先用 resample('H').mean() 聚合原始不规则采样,再 reindex,兼顾精度与效率。
可视化验证:绘制前检查 month_year_data_filled.isna().sum(),确认缺失时段数量符合预期;也可用 ax.axvspan() 标注已知空缺区间辅助验证。
通过这一标准化时间轴对齐流程,你将获得真正反映数据实际连续性的曲线图——每一段连线都对应真实采集的连续小时序列,彻底消除跨空缺的误导性连接。

















