I have a function that is supposed to enlarge all labels in a figure to make it ready for export. However I fail to enlarge the legend properly:
import matplotlib.pyplot as plt
def enlarge_legend(ax, fontSize = 25):
for text in ax.get_legend().get_texts():
text.set_fontsize(fontSize)
fig, ax = plt.subplots()
ax.scatter(
[1,2,3],
[2,3,1],
label = "auto"
)
ax.legend()
enlarge_legend(ax)
I would like the circle patch to be bigger as well but both ax.get_legend().get_patches() and ax.get_legend().get_lines()
return empty lists.
Any idea how to do it?
The dot in your legend is a PathCollection, so you have to tweak either markerscale when you create the legend, or the handle sizes after the legend exists.
fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [2, 3, 1], label='auto')
# option A – easiest: change legend as you make it
ax.legend(fontsize=25, markerscale=3) # ← “3” makes the dot ≈3× larger
or, with your current enlarge_legend helper:
def enlarge_legend(ax, size=25, marker_area=200):
lgd = ax.get_legend()
for txt in lgd.get_texts(): # enlarge text
txt.set_fontsize(size)
for h in lgd.legendHandles: # enlarge scatter marker
h.set_sizes([marker_area]) # area in points²
fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [2, 3, 1], label='auto')
ax.legend()
enlarge_legend(ax)
Either way the marker in the legend will grow to match (or exceed) the symbol size you see in the plot.