我正在尝试绘制一些时间轴,包括NaN和pyplot(参见示例代码)。问题是,当存在NaN时,pyplot不会在NaN之前和之后的点之间画一条线。有没有改变这种行为的解决方案? 我不想填写任何计算数据点而不是NaN。删除NaN也不是一种选择,因为这会导致x和y列表具有不同的长度。
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
y = [1, 2, 5, 4, 7, "nan", 4, 2, 5, 4, 4, 1]
plt.show(plt.plot(x, y, 'o-', linewidth = 0.5))
非常感谢, 儒略
答案 0 :(得分:1)
假设您实际上在谈论np.nan
,我经常通过以下方式解决此问题:
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
y = np.array([1, 2, 5, 4, 7, "nan", 4, 2, 5, 4, 4, 1], dtype=np.float64)
goods = ~np.isnan(y)
line = plt.plot(x[goods], y[goods], 'o-', linewidth = 0.5)
这样,您的x
和y
变量保持不变,但情节没有差距。请注意我:
x
和y
作为数组,以便它们可以通过布尔数组goods
y
成为np.float64
数组(以便'nan'
成为np.nan
)。如果你真的在谈论字符串'nan'(或者你想要排除的其他字符串),你可以这样做:
y = np.array([1, 2, 5, 4, 7, "nan", 4, 2, 5, 4, 4, 1])
goods = (y != "nan")
请注意,在这种情况下,我没有强制y
成为float64
,因此它最终成为|S21
。但是,matplotlib会在绘制之前将其转换为float64
(请查看line[0].get_xydata()
),因此一般来说,应用第一种方法可能最简单。否则,如果y
中的其他字符串无法转换为float64
,则matplotlib可能会抛出错误。
答案 1 :(得分:0)
我知道你说你宁愿不必删除" nan"。但是,我知道没有其他方法可以连接线路(无需插值或以某种方式填充数据)。因此,我怀疑最简单的选择可能是删除" nan"来自y
和x
中的相应索引。
>>> del x[y.index("nan")]
>>> x
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]
>>> y.remove("nan")
>>> y
[1, 2, 5, 4, 7, 4, 2, 5, 4, 4, 1]