Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib colorbar for scatter

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 = matplotlib.cm.get_cmap('RdYlBu') colors=[cm(1.*i/20) for i in range(20)] xy = range(20) plt.subplot(111) 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) plt.colorbar() plt.show() 

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

like image 427
Adam Greenhall Avatar asked May 19 '11 19:05

Adam Greenhall


People also ask

How do I change the color of a scatterplot in matplotlib?

To change the color of a scatter point in matplotlib, there is the option "c" in the function scatter.

How do you use the Colorbar in Python?

colorbar() in python. The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale. Parameters: ax: This parameter is an optional parameter and it contains Axes or list of Axes.


2 Answers

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 = plt.cm.get_cmap('RdYlBu') xy = range(20) z = xy sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm) plt.colorbar(sc) plt.show() 

Image Example

like image 116
matt Avatar answered Oct 05 '22 02:10

matt


Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots() im = ax.scatter(x, y, c=c) fig.colorbar(im, ax=ax) 
like image 30
neurite Avatar answered Oct 05 '22 03:10

neurite