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

Matplotlib绘图:忽略NaN值连接有效数据点,同时保留双组数据展示

解决Matplotlib中含NaN值数据的连线绘制问题

需求说明

需要绘制两组数据:

  • 含NaN值的观测数据Arealval:展示有效数据点标记,并用线条跳过NaN值连接有效点
  • 无NaN值的预测数据y:完整展示所有数据点与连线

此前手动筛选非NaN对应的x值实现效果,但大数据集下效率极低,需要程序化的自动处理方法。

最小可复现代码

import numpy as np
import matplotlib.pyplot as plt

x = [1.0, 3.0, 5.0, 7.0, 10.0, 15.0, 20.0]
y = [1.0, 3.0, 5.0, 7.0, 10.0, 5.0, 20.0]
Arealval = [30.1, np.nan, 33.4, np.nan, 22.4, np.nan, 35.8]

plt.plot(x, Arealval, marker='X', ls=':')
plt.plot(x, y, marker='o', ls=':')

plt.show()

解决方案

Matplotlib的plot函数原生支持自动识别并忽略NaN值:当传入的y数据中包含NaN时,函数会自动在NaN位置断开连线,仅连接有效数据点,同时只在有效数据的位置绘制标记。无需手动筛选数据,直接传入原始的x和含NaN的y数据即可实现需求。

如果需要更稳定的处理(比如针对更复杂的数据结构),可以将数据转换为numpy数组,效果一致:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1.0, 3.0, 5.0, 7.0, 10.0, 15.0, 20.0])
y = np.array([1.0, 3.0, 5.0, 7.0, 10.0, 5.0, 20.0])
Arealval = np.array([30.1, np.nan, 33.4, np.nan, 22.4, np.nan, 35.8])

plt.plot(x, Arealval, marker='X', ls=':', label='观测数据')
plt.plot(x, y, marker='o', ls=':', label='预测数据')
plt.legend()
plt.show()

运行上述代码后,观测数据的有效点会用X标记,且仅在有效点之间绘制虚线;预测数据则完整展示所有点与连线,完全符合需求。

内容的提问来源于stack exchange,提问作者David Siret Marqués

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:26:01