Home > Software engineering >  Matplotlib custom colors in scatter plot
Matplotlib custom colors in scatter plot

Time:06-23

I would like to know if there is some elegant way to set discrete colors in a scatter plot based on the value of the entry. For a completly simplified example:

x=np.arange(100)
plt.scatter(x,x,c=x,cmap='jet')
plt.show()

enter image description here

So let's say I want all values lower than 40 green, those between 40 and 60 green, and those larger than 60 to be red. I know that I could create a loop with some if statements that generates a list based on those conditions, so that I have something like colorlist=['blue','blue',.....].

enter image description here
I know that this works, but is there some different way of doing it, or is this the easiest way?

CodePudding user response:

You can do something like this:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as mcol

cmap = mcol.ListedColormap(["blue","green","red"])

bounds = [0, 40, 60, 100]
norm = mcol.BoundaryNorm(bounds, cmap.N)

x=np.arange(100)
plt.scatter(x,x,c=x,cmap=cmap,norm=norm)
plt.show()

enter image description here

For further details, take a look here:

  • Related