I am creating plots from an excel file as using pandas shown:
Here is the code that I am using:
ax1.plot(data2["E_x"], data2["E_y"], '--', color ='black', linewidth=2, label="Equi")
ax1.plot(data2["X"], data2["Y"], 'o', color ='black', markersize=8, label="Spinal Cord")
ax1.hlines(y=4500, xmin=0, xmax=4500, color ='black')
ax1.vlines(x=4500, ymin=0, ymax=4500, color ='black')
ax1.set_xlim([0,5000])
ax1.set_ylim([0,5000])
I would like to color the points inside the solid lines(<=4500) in green and outside in red. I have tried to do it as shown in previous answers by using np.where() or by using condition(for ex: <=4500), but it throws an error because the dimensions do not match(as can be seen from the plot.). What would be the best way to achieve the desired result?
Thanks in advance!
CodePudding user response:
If you use a scatter plot (as opposed to a line plot without lines) you can use the c
keyword to specify a list of colours for points. It is then easy to generate a list of keywords using a list comprehension.
You can even use the plotting that is built into pandas.
So instead of this line
ax1.plot(data2["X"], data2["Y"], 'o', color ='black', markersize=8, label="Spinal Cord")
use
data2.plot.scatter(x = 'X',
y = 'Y',
c = ['r' if x else 'g' for x in (data2.X < 4500) & (data2.Y < 4500)],
ax = ax1
)
You can still use matplotlib directly if you want
ax1.plot.scatter(x = 'X',
y = 'Y',
c = ['r' if x else 'g' for x in (data2.X < 4500) & (data2.Y < 4500)],
data = data2
)
Both of these should plot red inside the bounds and green outside.