可以使用掩模陣列:
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)
![enter image description here](https://i.stack.imgur.com/6d3oW.png)
但是,我認爲這可能不是你想要的。這裏是一個快速方法,可以將線路分爲兩個部分:
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)
![enter image description here](https://i.stack.imgur.com/p4ftX.png)
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)
上次在他們的文檔中,我查了一下。只是檢查出來。 – 2013-04-05 11:04:14
所以你想通過所有點但通過不同的線條樣式的一個情節? – 2013-04-05 11:11:20
@LevLevitsky:是的,這是正確的 – Brian 2013-04-05 11:31:50