您可以使用掩码数组:
import numpy as np
a=np.array([1,2,3,4,5,6,7,8,9])
b=np.array([-1,-2,-3,-4,-5,1,2,-3,-4])
plot(a, b)
m = b > 0
plot(np.ma.array(a, mask=m), np.ma.array(b, mask=m), 'r--', lw=2)
但是,我认为这可能不是您想要的。这是一种可以将线条分成两部分的快速方法:
import numpy as np
a=np.array([1,2,3,4,5,6,7,8,9])
b=np.array([-1,-2,-3,-4,-5,1,2,-3,-4])
x = np.linspace(a.min(), a.max(), 1000)
y = np.interp(x, a, b)
m = y <= 0
plot(np.ma.array(x, mask=m), np.ma.array(y, mask=m), 'b-', lw=2)
m = y > 0
plot(np.ma.array(x, mask=m), np.ma.array(y, mask=m), 'r--', lw=2)
np.interp()
将为大型数据集使用很多内存,这是另一种找到所有零点的方法。输出与上面相同。
idx1 = np.where(b[1:] * b[:-1] < 0)[0]
idx2 = idx1 + 1
x0 = a[idx1] + np.abs(b[idx1] / (b[idx2] - b[idx1])) * (a[idx2] - a[idx1])
a2 = np.insert(a, idx2, x0)
b2 = np.insert(b, idx2, 0)
m = b2 < 0
plot(np.ma.array(a2, mask=m), np.ma.array(b2, mask=m), 'b-', lw=2)
m = b2 > 0
plot(np.ma.array(a2, mask=m), np.ma.array(b2, mask=m), 'r--', lw=2)