Reputation: 2442
So I am using numpy.ma.masked methods to plot lines under certain condition, but I would like to connect all the consecutive lines. For example, using this code:
import pylab as plt
import numpy as np
x = np.linspace(0,10,100)
y = -1.0 + 0.2*x
plt.plot(x,np.ma.masked_greater_equal(y,0))
plt.plot(x,np.ma.masked_less_equal(y,0),'r')
I get the following result: So what is the smart way of connecting the lines so have a continuous line that changes its color?
Upvotes: 2
Views: 349
Reputation: 69116
Look at your values of y
. It looks like this:
array([-1. , -0.97979798, -0.95959596, -0.93939394, -0.91919192,
-0.8989899 , -0.87878788, -0.85858586, -0.83838384, -0.81818182,
-0.7979798 , -0.77777778, -0.75757576, -0.73737374, -0.71717172,
-0.6969697 , -0.67676768, -0.65656566, -0.63636364, -0.61616162,
-0.5959596 , -0.57575758, -0.55555556, -0.53535354, -0.51515152,
-0.49494949, -0.47474747, -0.45454545, -0.43434343, -0.41414141,
-0.39393939, -0.37373737, -0.35353535, -0.33333333, -0.31313131,
-0.29292929, -0.27272727, -0.25252525, -0.23232323, -0.21212121,
-0.19191919, -0.17171717, -0.15151515, -0.13131313, -0.11111111,
-0.09090909, -0.07070707, -0.05050505, -0.03030303, -0.01010101,
0.01010101, 0.03030303, 0.05050505, 0.07070707, 0.09090909,
0.11111111, 0.13131313, 0.15151515, 0.17171717, 0.19191919,
0.21212121, 0.23232323, 0.25252525, 0.27272727, 0.29292929,
0.31313131, 0.33333333, 0.35353535, 0.37373737, 0.39393939,
0.41414141, 0.43434343, 0.45454545, 0.47474747, 0.49494949,
0.51515152, 0.53535354, 0.55555556, 0.57575758, 0.5959596 ,
0.61616162, 0.63636364, 0.65656566, 0.67676768, 0.6969697 ,
0.71717172, 0.73737374, 0.75757576, 0.77777778, 0.7979798 ,
0.81818182, 0.83838384, 0.85858586, 0.87878788, 0.8989899 ,
0.91919192, 0.93939394, 0.95959596, 0.97979798, 1. ])
You'll notice that there is no value of 0.0
, thus the two lines will never touch.
You can resolve this by adding one more value to your x
array (i.e. 101 values, so you have a spacing of 0.1
, instead of 0.10101
. You also need to remove the _equal
from the masks, otherwise they will never touch (you currently mask out the value at y=0.
in both cases).
import pylab as plt
import numpy as np
x = np.linspace(0.,10.,101)
y = -1.0 + 0.2*x
plt.plot(x,np.ma.masked_greater(y,0.))
plt.plot(x,np.ma.masked_less(y,0.),'r')
Upvotes: 1