Search code examples
pythonmatplotlibscatter

Scatterplot change color of specific point


I am trying to create a scatter plot with quite a lot of points (>10000).

I want to highlight some of these points based on a certain condition by using a different color. I know that I could accomplish this by iterating through the points and specifying the color individually, but I think that this will be very slow.

Ultimately I want something which looks similar to this: enter image description here

I.e. Ideally I want to specify that the fifth point should be red.

Does anyone know if there is an easy way to accomplish this?

Furthermore, I would be very grateful if someone could tell me how I could add a legend to this kind of plot. E.g. that red dots mean "age>15" and blue dots "age<15"

Cheers!


Solution

  • You can solve it with this script

    import numpy as np
    from matplotlib import pyplot as plt
    
    fig,ax = plt.subplots()
    x = y = np.arange(20)
    colors = ['k'] * 20
    colors[4] = 'r'
    
    ax.scatter(x,y,c=colors)
    ax.scatter([],[],c='k',label='age < 15')
    ax.scatter([],[],c='r',label='age > 15')
    ax.legend(loc='best')
    

    The output figure is

    output