4

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.

HERE

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)

1 Answer 1

1

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) )

enter image description here

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate your help! I never knew about this scatteryoffsets option, and I'm glad I can sidestep creating custom artists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.