matplotlib 忽略缺失数据

matplotlib ignore missing data

这个问题已经被问过并且 good solution 使用掩码。

再次询问,因为我想知道是否有办法让 matplotlib 自行处理丢失的数据,比如如果缺少任何 x 或 y 数据,只需忽略它并在其中画一条线。

下面是一些示例代码:

import numpy as np
import matplotlib.pyplot as plt

plt.figure()

x = np.arange(0, 100, 10)
y = np.random.randint(0, 10, 10)
plt.plot(x,y, "*-")

x_nan = np.arange(100)
y_nan = np.asarray([np.nan] * 100)
y_nan[::10] = np.random.randint(0, 10, 10)
plt.plot(x_nan,y_nan,"*-")

mask = np.isfinite(y_nan)
plt.plot(x_nan[mask],y_nan[mask],"--")

plt.show()

第二个图只为非南点绘制点,但没有穿过它们的线。

让它看起来像第一个的最简单方法是像第三个图中那样定义一个掩码。我想知道是否有办法让 matplotlib 在没有额外掩码的情况下自动表现得像这样。

简答:否!

长答案:确实可以想象某些功能将内置到 matplotlib 的 plot 函数中,允许从输入中删除 nans。

不过,还有none。

但由于解决方案本质上只是多了一行代码,所以matplotlib不提供此功能这一事实是可以接受的。

还有一个有趣的事实:有趣的是,scatter 情节确实忽略了 nan 值,例如

line, = plt.plot(x_nan,y_nan,"-")
scatter = plt.scatter(x_nan,y_nan)
print(len(line.get_xdata()))       # 100
print(len(scatter.get_offsets()))  # 10

虽然直线仍然有 100 个点,但散点只有 10 个,因为所有 nan 值都被删除了。