[Matplotlib-users] Scatterplot with legend

Juan Nunez-Iglesias jni.soma at gmail.com
Fri Mar 4 02:32:52 EST 2016


All of the scatterplot legend examples that I can find on the web use
multiple calls to plt.scatter to then obtain a legend for each color, e.g.
here:

http://matplotlib.org/examples/lines_bars_and_markers/scatter_with_legend.html#lines-bars-and-markers-scatter-with-legend

However, I'm trying to make a single call to scatter, using a
ListedColorMap with three colors and passing c=(array of 0, 1, or 2) to the
plt.scatter call. Unfortunately, when I try to add a legend to this I get a
single point/value.

I tried to follow the proxy patch instructions here:
http://matplotlib.org/users/legend_guide.html#plotting-guide-legend

but couldn't get a circle when using patches.Circle() as the proxy object:
I still get a rectangular fill patch as in the examples above.

For completeness, two alternative examples:

========================

import numpy as np
from matplotib import pyplot as plt, patches, color

x = np.random.rand(50)
y = np.random.rand(50)
color = np.random.randint(3, size=50)

colormap = colors.ListedColormap([(1, 0, 0),
                                    (0, 0, 1),
                                    (0, 1, 0)])

pointtypes = np.array(['type 0', 'type 1', 'type 2'])

plt.figure()
plt.scatter(x, y, c=color, cmap=colormap)
plt.legend(pointtypes)


plt.figure()
plt.scatter(x, y, c=color, cmap=colormap)
proxy_artists = [patches.Circle((0, 1), color=colormap(i),
label=pointtypes[i]
                         for i in range(3)]
plt.legend(proxy_artists, pointtypes)

========================

Can anyone suggest a simple modification to obtain the above plot with the
right legend?

Thanks!

Juan.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/matplotlib-users/attachments/20160304/75c18cf6/attachment.html>


More information about the Matplotlib-users mailing list