python - How to plot with different linestyles in pylab -
i have these 2 numpy
arrays
import numpy 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])
i can plot them so
pylab import * plot(a,b,'b-',lw=2)
i show points negative b
different linestyles, instance dashed line.
i this
plot(a[(b<0)],b[(b<0)],'b--',lw=2)
but connects points in single line. instance, don't want point a=5 , b=-4 connected point a=8 , b=-3
you can use mask array:
import numpy 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)
however, think maybe not want. here quick method can split lines 2 parts:
import numpy 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()
use many memory large dataset, here method find 0 points. output same above.
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)
Comments
Post a Comment