Fix Python – matplotlib colorbar for scatter


Asked By – Adam Greenhall

I’m working with data that has the data has 3 plotting parameters: x,y,c. How do you create a custom color value for a scatter plot?

Extending this example I’m trying to do:

import matplotlib
import matplotlib.pyplot as plt
cm ='RdYlBu')
colors=[cm(1.*i/20) for i in range(20)]
xy = range(20)
colorlist=[colors[x/2] for x in xy] #actually some other non-linear relationship
plt.scatter(xy, xy, c=colorlist, s=35, vmin=0, vmax=20)

but the result is TypeError: You must first set_array for mappable

Now we will see solution for issue: matplotlib colorbar for scatter


From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now.
plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns.
vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

How does this work for you?

import matplotlib.pyplot as plt
cm ='RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)

Image Example

This question is answered By – matt

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0