I am looking for a way to include a (matplotlib) legend that describe the size of points in a scatter plot, as this could be related to another variable, like in this basic example:
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
a2 = 400*np.random.rand(N)
plt.scatter(x, y, s=a2, alpha=0.5)
plt.show()
(inspired from: http://matplotlib.org/examples/shapes_and_collections/scatter_demo.html)
so in the legend there would be ideally few spots corresponding to sizes 0-400 (the a2
variable), according to s
descriptor in scatter
.
I found this here, it is so easy and concise. Hope it helps
The solution below used
pandas
to group the sizes together into set bins (withgroupby
). It plots each group and assigns it a label and a size for the markers. I have used the binning recipe from this question.Note this is slightly different to your stated problem as the marker sizes are binned, this means that two elements in
a2
, say 36 and 38, will have the same size as they are within the same binning. You can always increase the number of bins to make it finer as suits you.Using this method you could vary other parameters for each bin, such as the marker shape or colour.
This'll also work, and I think it's a bit simpler:
Taken from: Point size legends in matplotlib and basemap plots
Building on mjp's and jpobst's answers, if you have more than two discrete sizes you can make a loop and include the labels in the call to plt.scatter():
Note that you can format the label using standard string formatting, such as
label = ('M%d' %size)
for the labels in mjp's answer.I almost like mjp's answer, but it doesn't quite work because plt.plot's 'markersize' argument doesn't mean the same thing as plt.scatter's 's' argument. Your sizes will be wrong using plt.plot.
Instead use: