该问题已被提出,并且有 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
函数中会内置一些功能,允许从输入中删除 nan
。
但是,没有。
但由于解决方案本质上只是多一行代码,所以 matplotlib 不提供此功能的事实是可以忍受的。
正如一个有趣的事实:有趣的是,散点
图确实忽略了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 值都被删除。
关于python - matplotlib 忽略缺失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48637793/