在线图中设置间隙/中断

时间:2013-03-27 05:32:05

标签: python matplotlib

我有一个有效“连续”传感器读数的数据集,偶尔会出现间隙。

然而,有几个时期没有记录数据。这些差距明显长于样本期。

默认情况下,pyplot将每个数据点连接到下一个数据点(如果我有一个线型设置),但是当我连接长间隙两侧的两个数据点时,我觉得这有点误导。

我宁愿在那里没有线路;也就是说,我希望这条线能够停下来并在差距之后重新开始。

我尝试使用y值None添加这些间隙部分中的元素,但似乎将该行发送回图的前一部分(尽管奇怪的是这些行根本没有出现缩放级别。。

我想到的另一个选择是简单地用plot单独调用每个部分,但这会有点丑陋和麻烦。

是否有更优雅的方法来实现这一目标?

编辑:下面是一个演示行为的最小工作示例。第一个图是我试图避免的连接线。第二个图表显示添加None值似乎有效,但是如果平移视图的视图,则会得到第三个图中显示的内容,一条线跳到图的前面部分。

import numpy as np
import matplotlib.pyplot as plt

t1 = np.arange(0, 8, 0.05)
t2 = np.arange(10, 14, 0.05)
t = np.concatenate([t1, t2])
c = np.cos(t)

fig = plt.figure()
ax = fig.gca()
ax.plot(t, c)
ax.set_title('Undesirable joining line')


t1 = np.arange(0, 8, 0.05)
t2 = np.arange(10, 14, 0.05)
c1 = np.cos(t1)
c2 = np.cos(t2)
t = np.concatenate([t1, t1[-1:], t2])
c = np.concatenate([c1, [None,], c2])

fig = plt.figure()
ax = fig.gca()
ax.plot(t, c)
ax.set_title('Ok if you don\'t pan the plot')

fig = plt.figure()
ax = fig.gca()
ax.plot(t, c)
ax.axis([-1, 12, -0.5, 1.25])
ax.set_title('Strange jumping line')

plt.show()

Plot 3, the "strange jumping line"

1 个答案:

答案 0 :(得分:12)

蒙面数组适用于此。您只需掩盖您不想连接的第一个点:

import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt

t1 = np.arange(0, 8, 0.05)
mask_start = len(t1)
t2 = np.arange(10, 14, 0.05)
t = np.concatenate([t1, t2])
c = np.cos(t)     # an aside, but it's better to use numpy ufuncs than list comps

mc = ma.array(c)
mc[mask_start] = ma.masked
plt.figure()
plt.plot(t, mc)
plt.title('Using masked arrays')

plt.show()

enter image description here

至少在我的系统(OSX,Python 2.7,mpl 1.1.0)上,我没有任何平移等问题。