Change color of scatter points depending on limits/condition

Viewed 713

I am creating plots from an excel file as using pandas shown: Scatter Plot

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!

Link to sample data.

2 Answers

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 colour for each point. It is then easy to generate a list of keywords using a list comprehension for each data point based on whatever criteria you want.

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.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.

When using a filter, the same filter should be used for x as well as for y. That way, both keep the same length. You can use ~ to take the opposite of a given filter. Here is an example:

from matplotlib import pyplot as plt
import numpy as np

fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.plot([0, 5000], [0, 5000], '--', color='black', linewidth=2, label="Equi")
x = np.random.uniform(500, 5000, 50)
y = x + np.random.normal(0, 300, len(x))
filter = (x < 4500) & (y < 4500)
ax1.plot(x[filter], y[filter], 'o', color='lime', markersize=8, label="Spinal Cord")
ax1.plot(x[~filter], y[~filter], 'o', color='crimson', 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])

plt.tight_layout()
plt.show()

coloring points depending on conditions

Related