2
votes

I have a scatter plot in matplotlib. The scatter plot shows circles with different shades of color and also different sizes.

I would like to add a legend only for the size of the circles. The legend should not be colored by the color of the cirlcles in the plot, but rather have say a 'grey' color. Then there should be three entries corresponding to a big grey circle, medium grey circle, and small grey circle, all with some text. In one legend entry, I only need a single circle, not multiple circles that seems to be default in matplotlib.

How can I do this?

I've tried this based on this http://matplotlib.org/users/legend_guide.html,

but it gives a rectangle, rather than a circle.

red_patch = mpatches.Circle((3,3), radius = 1000, color='blue', label='The red data')
ax1.legend(handles=[red_patch])
1
Most of that is done in the answer here, except changing the legend marker color. I'll think about that. - cphlewis

1 Answers

5
votes

Doing as much of the work automatically as possible:

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

ll = plt.scatter(random(10), random(10), s=random(10)*10, marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), s=random(10)*20, marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), s = random(10)*300, marker='o', color=colors[2])
z  = plt.scatter(random(10), random(10), s = 35, marker='+', color=colors[3]) # not in legend

gll = plt.scatter([],[], s=10, marker='o', color='#555555')
gl = plt.scatter([],[], s=20, marker='o', color='#555555')
ga = plt.scatter([],[], s=300, marker='o', color='#555555')

plt.legend((gll,gl,ga),
       ('10', '20', '300'),
       scatterpoints=1,
       loc='lower left',
       ncol=1,
       fontsize=8)

plt.show()

enter image description here

could be niced up with looping over sizes=[10,20,300] or such.