4

I am basically plotting a scatter graph with matplotlib, however, I have varied each point by a radius.

When I use plt.legend() to show my legend, it looks like this...... enter image description here

Is there a command to reduce the size of the circle. I know this is probably a very trivial question, and I have tried searching it!

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
mcstosh
  • 71
  • 1
  • 2
  • 8

3 Answers3

5

The solution may depend on whether the markers in the legend should be scaled compared to the original size or whether a constant marker size independent on the original size is desired.

A. Scale the markers

You may use the legend.markerscale rcParam.

plt.rcParams["legend.markerscale"] = 0.3

or the markerscale argument to the legend.

plt.legend(markerscale=0.3)

From the legend documentation:

markerscale : None or int or float

The relative size of legend markers compared with the originally drawn ones. Default is None which will take the value from the legend.markerscale rcParam.

Example:

import matplotlib.pyplot as plt
plt.rcParams["legend.markerscale"] = 0.3

plt.scatter([.3,.5], [.3,.6], s=1000, label="label")
plt.scatter([.7,.4], [.3,.6], s=81, marker="^", label="label2")
plt.legend()
plt.show()

enter image description here

Note that this will scale all markers simultaneously.

B. Set a constant marker size

In case you want a constant marker size in the legend, independent on the actual size of the scatter points, the solution is slightly more complicated. You may use the legend's handler_map to set the desired marker size to the legend handles.

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerPathCollection

sc = plt.scatter([.3,.5], [.3,.6], s=1000, label="label")
plt.scatter([.7,.4], [.3,.6], s=[100,300], marker="^", label="label2")

marker_size = 36
def update_prop(handle, orig):
    handle.update_from(orig)
    handle.set_sizes([marker_size])

plt.legend(handler_map={type(sc): HandlerPathCollection(update_func=update_prop)})
plt.show()

enter image description here

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
3

this worked for me:

# Legend
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, framealpha=1, ncol=1, 
            bbox_to_anchor=(1.02,1), loc=2, fontsize=8, borderaxespad=0.)

for legend_handle in lgd.legendHandles:
    legend_handle.set_sizes([50])
Gabriel
  • 525
  • 1
  • 5
  • 8
1

Have you tried this as described here?

params = {'legend.linewidth': 2}
plot.rcParams.update(params)
schnobi1
  • 66
  • 3