Reputation: 171
I'm making a couple scatter plots in matplotlib with a legend. The marker sizes are small, so plotting just a few example points in the legend handle will be hard to see. Instead, I want to format the legend handles to look like tiny scatter plots (i.e., little circular-ish clouds of points).
I know it's possible to change the scatterpoints keyword when calling the legend, as in the figure (figure and code below), and this sort of does what I want, but the handles seem to be grouping along a semi-horizontal line, and I'd like them to look more randomized than this.
I've looked for another thread that covers this topic but haven't had much luck. I know it will involve creating a custom artist, and this thread gives some insight into that: How to make custom legend in matplotlib.
Thanks in advance for any help.
import matplotlib.pyplot as mp
import numpy
a = numpy.random.rand(1000)
b = numpy.random.rand(1000)
c = numpy.random.rand(1000)
d = numpy.random.rand(1000)
fontsize=12
fig = mp.figure(figsize=(3,3))
ax = fig.add_subplot(111)
ax.scatter(a, b, color='0.25', s=1, label='label1')
ax.scatter(c, d, color='firebrick', s=1, label='label2')
ax.tick_params(labelsize=fontsize)
handles, labels = ax.get_legend_handles_labels()
leg = ax.legend(handles, labels, fontsize=fontsize, scatterpoints=10, bbox_to_anchor=(1.03,1.0), bbox_transform=ax.transAxes, loc='upper left', borderaxespad=0, labelspacing=0.25, fancybox=False, edgecolor='0', framealpha=0, borderpad=0.25, handletextpad=0.5, markerscale=1, handlelength=0)
Upvotes: 4
Views: 1814
Reputation: 339660
The legend has a scatteryoffsets
argument. You can supply a list of y coordinates. Those should be between 0 and 1.
yoffsets = [.1,.7,.3,.1,.8,.4,.2,.6,.7,.5]
plt.legend(scatteryoffsets=yoffsets, scatterpoints=len(yoffsets) )
import matplotlib.pyplot as plt
import numpy
import matplotlib.legend_handler
import matplotlib.collections
a = numpy.random.rand(1000)
b = numpy.random.rand(1000)
c = numpy.random.rand(1000)
d = numpy.random.rand(1000)
fontsize=12
fig = plt.figure(figsize=(3,3))
ax = fig.add_subplot(111)
sc = ax.scatter(a, b, color='0.25', s=1, label='label1')
sc2 = ax.scatter(c, d, color='firebrick', s=1, label='label2')
ax.tick_params(labelsize=fontsize)
yoffsets = [.1,.7,.3,.1,.8,.4,.2,.6,.7,.5]
plt.legend(scatteryoffsets=yoffsets, scatterpoints=len(yoffsets),
framealpha=1)
plt.show()
Upvotes: 1