Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Legend Marker Size: How to Change It After Plotting?

Learn how to adjust legend marker size in matplotlib using markerscale or directly modifying legend handles and text.
Before and after matplotlib plot showing how to change legend marker size for better visibility Before and after matplotlib plot showing how to change legend marker size for better visibility
  • Using markerscale lets you change legend marker sizes without changing the plot markers.
  • You can adjust legend handles after plotting for fine control of visual parts.
  • Making legends by hand helps with complex layouts or different marker types.
  • Custom legend handlers like HandlerLine2D give you more ways to change how things look.
  • Doing things wrong with objects (like using marker settings on patches) can cause errors.

To make clear and professional plots with matplotlib, you often need to adjust small things. The chart's legend is one of these. A common problem is that marker sizes in legends don't always match the plot. They might look too small to see well or too big and odd. Poor marker size can make the chart hard to read and look messy. In this guide, you'll learn how to change legend size, control how markers look, and use good practices with matplotlib.legend(). This includes changing markerscale, editing legend handles directly, and even building custom legends with Line2D and handler classes.


What Legends Do in matplotlib

In matplotlib, legends are like visual summaries. They connect labels to graphic parts like lines, markers, or shapes. When you use plt.legend() or ax.legend(), matplotlib collects details from the plot's visual parts, such as those made with ax.plot(), ax.scatter(), or ax.bar(). Then it fills in a legend.

Usually, the legend tries to look just like the plot's visual parts, including their marker type, color, and size. But this might not always fit how you want things to look. For example, if your plot uses small markers for accuracy, the automatic legend might show markers too tiny for people to understand, especially in talks or printed papers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To help with this, matplotlib gives you tools to change how the legend looks apart from the main plot. The most important tool is being able to change legend size and adjust marker size.


Why Change Legend Marker Size?

Changing the size, scale, and how easy your legend is to read is key for good-looking charts. Here are some reasons why you might need to change legend marker size:

  • 📊 Easy to See on Big Screens: Small markers are hard to see on projector screens or when zoomed in during talks.
  • 🖨️ Clear in Printed Papers: School papers, books, or printed reports need legends that are clear and sharp. Wrong sizes are easy to spot here.
  • 📈 Charts Look the Same: Reports with many small charts or similar themes look messy if legend sizes aren't standard.
  • 🧑‍💻 Helps People See Better: Bigger markers make charts easier to see for people who have trouble with their sight.

Making your legends easy to scale and read makes charts better for people to use and look more professional.


Using the markerscale Setting in matplotlib.legend

One of the simplest ways to fix marker sizes that don't match in your legend is to use the markerscale setting.

plt.legend(markerscale=2.0)

🔍 How It Works

The markerscale setting multiplies the original marker size used in the main plot by the number you give it. This changes the size only for the legend. It does not change how the markers look in the plot itself.

For example, if your plot has markers with a size of 6, putting markerscale=2.0 with your legend will show those markers at size 12 in the legend.

✅ When to Use This

  • Use this when plot markers are small but should stand out in the legend.
  • Use this when you need to make markers easier to see for people who have trouble seeing.
  • Use this when having a clear legend is more important than the legend markers looking exactly like the plot markers.

💡 Quick Advice

For scatter plots or charts with many markers, a markerscale of 1.5 to 2.5 makes the legend easier to read without making it look too crowded.


Changing Legend Marker Size After Plotting

Maybe you already made a plot and used plt.legend(). It might seem like you can't change how it looks now, but you can. matplotlib lets you get to the legend object to make changes later.

Get and Change Legend Handles

legend = ax.get_legend()
for handle in legend.legendHandles:
    handle.set_markersize(10)

This way lets you have exact control. You can change marker size right away after the plotting is done. This is helpful when you are updating plots live in places like interactive notebooks or dashboards.

Working with Axes Objects

If you are using matplotlib's object-oriented way (which is good for more complex plots), get the legend from the Axes object:

fig, ax = plt.subplots()
# ... plot calls ...
legend = ax.legend()
for handle in legend.legendHandles:
    handle.set_markersize(8)

By changing the legend separately from the plot, you get control over the visuals piece by piece. And it becomes simpler to use this method on many charts.


Changing Legend Handles Directly: Hands-on with Line2D

Sometimes you need more control than markerscale gives you. This is true when you want to change more than just marker size, like style, color, or line thickness. This is where changing Legend Handles right away is useful.

from matplotlib.lines import Line2D

legend = ax.get_legend()
for line in legend.legendHandles:
    if isinstance(line, Line2D):
        line.set_markersize(12)

This involves:

  • Getting the items inside legendHandles.
  • Finding out what type they are (for example, Line2D).
  • Changing specific things like set_markersize(), set_markerfacecolor(), and set_markeredgewidth().

Common Uses

  • Changing colors to match themes or color sets.
  • Changing marker size only when certain things are true.
  • Making some items in legends stand out or look less important.

By changing Line2D objects, you get almost total control over how things look in your legend.


Making Legends Again with Custom Handles

Often, complex plots need a legend made just for them. This kind of legend does not use the automatic way of gathering handles. matplotlib lets you make your own handles and labels before you use the legend() function.

custom_handles = [
    Line2D([], [], color='blue', marker='o', linestyle='', markersize=12, label='Category A'),
    Line2D([], [], color='green', marker='s', linestyle='', markersize=12, label='Category B')
]

ax.legend(handles=custom_handles, fontsize=10, loc='upper right')

Good Things About This

  • You have total control over marker type, color, size, and if lines are there.
  • It helps handle complex or mixed plots cleanly.
  • It's easier to make things look how you want (like matching brand colors).

This method helps a lot when you have many sets of data or when you put bars, lines, and scatter points together in one chart.


Making the Legend Look Good: Font Size and Spacing

If your legend markers are the right size, but the legend looks too tight or not lined up, other settings can help.

plt.legend(markerscale=1.8, fontsize=12, labelspacing=0.5, handlelength=2.0)

Setting Details

  • fontsize: Controls how big the legend label text is.
  • labelspacing: Sets how much space is between rows in the legend.
  • handlelength: Changes the length of legend lines (affects the whole part).

What You Get: Easier to Read

These changes make sure the legend marker and text are balanced. This makes the visual not just right, but also professional and simple to understand right away.


Using HandlerLine2D for More Custom Legend Looks

For special cases and detailed visuals, matplotlib offers HandlerLine2D from matplotlib.legend_handler. This lets you change exactly how legend items are drawn.

from matplotlib.legend_handler import HandlerLine2D

line, = ax.plot([1, 2, 3], [1, 4, 9], marker='x', label='Data X')
ax.legend(handler_map={line: HandlerLine2D(numpoints=1)})

Main Benefit

Usually, matplotlib shows two markers per legend line. HandlerLine2D(numpoints=1) changes this. It shows only one marker per legend item. This can look nicer or match your visual plan better.

These handlers are part of how matplotlib draws things. They are great for work that needs to be ready for printing in papers or books.


Common Things to Watch Out For

While changing matplotlib legends gives you freedom, some mistakes can lead to confusing or broken charts. Here's what to be careful about:

⚠️ Problem 🚫 Why It Happens
Trying to use set_markersize() on a Patch This causes an AttributeError. Patch objects don't have marker functions.
Forgetting to show the changes If you use interactive tools (like Jupyter), legend changes might not show until you draw it again.
Using the same legend again Making legends automatically in loops can create old or wrongly lined-up visuals.
Markers and labels don't match Labels that don't fit the markers can make legends confusing or hard to understand.

Always check your final chart where you plan to use it—on a screen, in a PDF, or in a slide deck. Things might look different.


An Example from the Real World

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [1, 3, 5]

fig, ax = plt.subplots()
line1, = ax.plot(x, y1, marker='o', label='Group 1')
line2, = ax.plot(x, y2, marker='s', label='Group 2')

# Change legend size and font
ax.legend(markerscale=2.0, fontsize=12)

plt.savefig('legend-adjusted.png', dpi=300)

The Result

This example makes the legend marker size double. This makes it much clearer. It's great for publishing or giving talks. The savefig() command makes sure the changes are saved in the image file.


Making Sure Legends Look the Same Across Projects

If you make many charts, using the same style repeatedly can make things look the same and cut down on mistakes. You can set up a function to apply a standard look.

def apply_custom_legend(ax):
    ax.legend(markerscale=1.8, fontsize=11, labelspacing=0.4, handlelength=2.5)

Use this function on any axes object you work with. This helps your charts keep the same visual style.


Quick Look Back

Here is a fast summary of when to use each way to change legend marker size:

Situation Best Way
Need a quick increase in marker size Use the markerscale setting
Need to adjust after plotting Use ax.get_legend() then set_markersize()
Need to make the legend look quite different Use custom handles with Line2D
Need to show only one marker Use HandlerLine2D with numpoints=1
Want the same style for many charts Write a function to do it

Last Things to Think About

Knowing how to change legends in matplotlib is important for making charts that are clear, easy for everyone to see, and look good. Whether you need to just slightly change marker sizes with markerscale, make exact changes by working with handles directly, or build legend items from scratch for complex data, matplotlib gives you the tools and freedom to do it well. Take the time to make legends that are easy to read. Your audience will like them better. They will understand the charts with fewer mistakes, and they will trust your data visuals more.

Find more tips on changing visuals in our other guides:


Sources

Hunter, J. D. (2007). Matplotlib: A 2D graphics environment. Computing in Science & Engineering, 9(3), 90–95. https://doi.org/10.1109/MCSE.2007.55

matplotlib.pyplot.legend. (n.d.). In Matplotlib documentation. Retrieved from https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading