Skip to main content
v2026.11,986 entries · CC-BY 4.0

Legend Text Size in Matplotlib: Labels and Titles

Set Matplotlib legend labels and titles independently, use shared defaults, and check the resulting font sizes in a synthetic assay example.

Written and maintained by CASRAI Editorial Board

Published

On this page

Set legend text size in Matplotlib with ax.legend(fontsize=12): numeric sizes are in points. Use title_fontsize for the legend title. If you also pass prop, put the label size inside that font-properties dictionary because it overrides fontsize.

The example below separates label text, title text and existing legend objects, then checks their actual sizes in code. It uses an explicitly synthetic assay time course so you can adapt the plotting commands to research data without confusing the demonstration values with experimental findings.

What it is used for in research

Legend typography helps readers connect a named group with its plotted series. Matplotlib takes automatic legend entries from the labels attached to plotted artists. Changing their font size changes the key’s text; it does not rename the groups or change the observations. Treat those as separate tasks when preparing an analysis figure.

For a figure script, a useful division is to specify the group labels where the lines are created and specify typography where the legend is created. That keeps the scientific meaning beside the data mapping and the appearance settings together. When the same script produces several panels, a shared default can reduce repeated formatting arguments.

This guide concentrates on text. If the larger key needs a different position, use the separate guide to Matplotlib legend placement and outside legends. Moving a legend and enlarging its labels solve different problems, even when you need both changes in the final figure.

Install or access Matplotlib

The official installation guide gives pip install matplotlib and the interpreter-specific upgrade command below. Run installation commands in a terminal, then run the Python examples in the environment used for your analysis.

python -m pip install -U matplotlib

If an attempted source build fails, the official guide describes adding --prefer-binary to select an available wheel. Its noninteractive backends include Agg, PDF and SVG, so a workflow that saves figures can work without opening a graphical window. Installation and display configuration are separate from the legend arguments.

For package and interpreter troubleshooting, see installing Matplotlib with pip. Once your plotting environment imports matplotlib.pyplot, no additional legend-font package is needed for the controls shown here.

Step-by-step task: size a research figure legend

Use the following numbered workflow to create the labels, set the two text sizes and inspect the result. The point sizes are example settings, not journal requirements. The observations form an illustrative composite: they are invented values for demonstrating software and do not describe a real assay.

  1. Create a figure and Axes, and keep the Axes reference as ax.
  2. Plot each group with an explicit label. These labels become the legend entries.
  3. Call ax.legend(fontsize=12, title='Group', title_fontsize=13) and retain the returned legend as leg.
  4. Read the entry sizes through leg.get_texts() and the title through leg.get_title().
  5. Save the figure after the typography is set. Inspect the labels and their series mapping in the output.
import matplotlib.pyplot as plt

# Illustrative composite: synthetic observations, not research findings.
time_h = [0, 2, 4, 6]
control = [0.10, 0.16, 0.25, 0.36]
treated = [0.10, 0.14, 0.19, 0.25]

fig, ax = plt.subplots()
ax.plot(time_h, control, marker='o', label='Control')
ax.plot(time_h, treated, marker='s', label='Treated')
ax.set_xlabel('Time (h)')
ax.set_ylabel('Illustrative signal (arbitrary units)')

leg = ax.legend(fontsize=12, title='Group', title_fontsize=13)
label_sizes = [text.get_fontsize() for text in leg.get_texts()]
title_size = leg.get_title().get_fontsize()
print(label_sizes, title_size)
assert label_sizes == [12.0, 12.0]
assert title_size == 13.0

fig.savefig('legend-text-size-example.png')
plt.close(fig)

The expected printed values are [12.0, 12.0] 13.0. Those values describe font sizes, not measurements from the time course. The assertions check both group labels and the title independently; this makes a partial formatting change visible when you adapt the example.

Replace the two observation lists and their group names together when using your own data. Keep the inspection block while adjusting typography. An assertion about appearance is useful evidence of the intended setting, but it does not validate the underlying analysis or the choice of plotting method.

Matplotlib legend fontsize and font properties

Use fontsize for a size-only change. Use prop when you want a group of label-font settings. The official legend API makes the precedence explicit: the separate fontsize argument applies only when prop is not specified.

# Alternative legend call on an Axes containing labelled artists:
leg = ax.legend(
    prop={'size': 12, 'weight': 'bold'},
    title='Group',
    title_fontsize=13
)

Put size in the properties dictionary when you also specify a weight or family there. Keeping one source of label-size configuration avoids a misleading call that contains two apparently competing values. For example, a call with fontsize=16 and prop={'size': 10} uses the properties setting for the labels.

Size the legend title separately

The legend title has its own title_fontsize argument. To combine its size with other font settings, use title_fontproperties={'size': 13, 'weight': 'bold'} instead. Do not combine title_fontsize and title_fontproperties; the documentation treats those controls as mutually exclusive.

Consequently, a dictionary for entry fonts does not replace the title’s dictionary. In a reproducible figure script, name the group heading and choose its typography explicitly rather than assuming it will track a label-size edit. The title is also available as a separate Text object for later changes.

Numeric points versus relative size names

A numeric fontsize is an absolute point size. Documented strings include 'small', 'medium' and 'large', which are relative to the current default font size. A relative word therefore does not identify one fixed point size across every configuration.

For this walkthrough, explicit numbers make the assertions straightforward. Relative names remain useful when you deliberately want the legend to follow the figure’s broader typography. Record which approach you use in the plotting code so a later style change has a clear interpretation.

You can demonstrate that distinction without changing any observations. The following check constructs the same labelled series under two different base font settings. It records the resolved size of 'small', then creates a legend with an explicit numeric size. The test asks whether the relative size increased and whether the absolute size stayed fixed; it does not assume a particular conversion factor.

import matplotlib as mpl

relative_sizes = []
for base_size in (10, 20):
    with mpl.rc_context({'font.size': base_size}):
        fig, ax = plt.subplots()
        ax.plot([0, 1], [0, 1], label='Example series')
        relative = ax.legend(fontsize='small')
        relative_sizes.append(relative.get_texts()[0].get_fontsize())
        absolute = ax.legend(fontsize=12)
        assert absolute.get_texts()[0].get_fontsize() == 12.0
        plt.close(fig)
assert relative_sizes[1] > relative_sizes[0]

This is a controlled software example: only the base font setting changes between iterations. In an analysis notebook, that distinction helps explain why a relative legend label may look different after a broader font configuration change. Keep explicit local sizes when fixed values are the intention, or keep relative names when coordinated scaling is the intention.

Set legend defaults for a figure series

Use legend.fontsize and legend.title_fontsize in the runtime configuration when several legends should share settings. Matplotlib’s customization guide explains that rcParams hold the active defaults and can be changed temporarily with a context manager.

import matplotlib as mpl
import matplotlib.pyplot as plt

with mpl.rc_context({'legend.fontsize': 12,
                     'legend.title_fontsize': 13}):
    fig, ax = plt.subplots()
    ax.plot([0, 1], [0, 1], label='Example series')
    leg = ax.legend(title='Group')
    fig.savefig('legend-defaults-example.png')
    plt.close(fig)

Create the legend inside the context so it uses those defaults. The rc_context documentation states that configuration changes are reset on exit, except for the backend setting. This scoped approach is useful for a plotting function that should not leave font defaults changed for later work in the same session.

The downloadable data table compiles the controls by scope: creation arguments, defaults and existing text objects. It also records the important precedence caveats. Use that compilation to identify which setting your script is actually using before adding another formatting command.

Output and how to read it

The first example produces two legend entries, Control and Treated, under the heading Group. The entries should report 12-point fonts and the heading 13 points. Check names and symbols as well as sizes: an attractive legend is only useful if each entry still identifies the intended series.

The Legend API returns the entry Text objects through get_texts() and the title Text object through get_title(). Text supplies get_fontsize() and set_fontsize(), so you can inspect or change an existing legend without constructing another one.

# Apply to the leg returned by an existing legend call.
for text in leg.get_texts():
    text.set_fontsize(11)
leg.get_title().set_fontsize(12)

print([text.get_fontsize() for text in leg.get_texts()])

Save the figure after these edits if they should appear in the saved output. This mutation approach is useful when your plotting function already returned a legend. Keeping that reference also makes it clear which legend is being edited when a script builds more than one figure.

Troubleshooting legend text size

The fontsize argument appears to have no effect

Look for a prop argument first. Remove it for a size-only call, or move the intended size into its dictionary. Inspect the actual label sizes afterward instead of deciding only from the plot window.

The labels change but the heading does not

Change the title through title_fontsize, or edit leg.get_title(). If using a title-properties dictionary, place its size there and omit the separate title-size argument.

The legend is empty or a group is missing

Check the artist labels before adjusting typography. The automatic legend mechanism excludes labels that start with an underscore. Set explicit labels on the plotted artists, or provide the handles and labels you intend the legend to display.

The text changes but the markers remain too small

Text size and marker size have separate controls. The legend’s markerscale changes markers relative to their plotted originals. For the original plotted symbols, see Matplotlib marker sizing; for line strokes, see Matplotlib line thickness.

The larger legend takes more space

Several spacing arguments, including labelspacing, handletextpad and borderpad, are expressed in font-size units. Inspect the whole key after changing its text. Adjusting spacing or placement is a separate decision from changing the point size.

Free alternatives

Plotly’s open source Python graphing library provides another legend-formatting workflow. Its official page states that the library uses the MIT license, works offline and requires no account registration. The table compares its two Python interfaces; they are interfaces to the same library.

Interface Legend text control Documented entry behaviour
Plotly Express Apply a legend font dictionary through fig.update_layout(legend={'font': {'size': 12}}). Express generates traces and legend entries from the discrete mappings in its plotting call.
Plotly graph objects Use the same layout legend font dictionary on a graph-objects figure. Trace name supplies the legend entry name; clicking legend items can show or hide traces.

These are alternatives when you are already building a Plotly figure. Their layout dictionary is not a Matplotlib legend argument: keep each library’s syntax with its own figure objects. For an existing Matplotlib script, the creation, default and Text-object methods above provide the direct controls.

Sources

Data: Matplotlib legend text size controls by scope

Original compilation of legend creation arguments, runtime defaults and existing Text-object methods. Combines the official legend, text, customization and context-manager references to distinguish affected text and precedence caveats.

Matplotlib legend text size controls by scope
ControlScopeAffected text or settingInputCaveatSource reference
fontsizeLegend creationEntry textNumeric points or relative size nameUsed only when prop is absentpyplot.legend
propLegend creationEntry font propertiesDictionary or FontPropertiesPut size in this object when using itpyplot.legend; Legend API
title_fontsizeLegend creationTitle textNumeric points or relative size nameDo not combine with title_fontpropertiespyplot.legend
title_fontpropertiesLegend creationTitle font propertiesDictionary or FontPropertiesPut size here with other title font settingspyplot.legend
legend.fontsizeRuntime defaultsNew legend entry textrcParams settingConfigure before constructing the legendCustomization guide; Legend API
legend.title_fontsizeRuntime defaultsNew legend title textrcParams settingExplicit title arguments provide local controlCustomization guide; pyplot.legend
get_texts() + set_fontsize()Existing legendEntry Text objectsNumeric points or relative size nameIterate entry Text objects returned by get_textsLegend API; Text API
get_title() + set_fontsize()Existing legendTitle Text objectNumeric points or relative size nameEdit title Text separately from entriesLegend API; Text API
rc_contextScoped defaultsRuntime configurationDictionary of rcParamsRestores changed rcParams on exit except backendrc_context reference; Customization guide

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Legend Text Size in Matplotlib: Labels and Titles

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →