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.
- Create a figure and Axes, and keep the Axes reference as
ax. - Plot each group with an explicit
label. These labels become the legend entries. - Call
ax.legend(fontsize=12, title='Group', title_fontsize=13)and retain the returned legend asleg. - Read the entry sizes through
leg.get_texts()and the title throughleg.get_title(). - 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
- Matplotlib, pyplot.legend reference. Checked 2026-11-14.
- Matplotlib, Legend API. Checked 2026-11-14.
- Matplotlib, Installation guide. Checked 2026-11-14.
- Matplotlib, Customizing with style sheets and rcParams. Checked 2026-11-14.
- Matplotlib, rc_context reference. Checked 2026-11-14.
- Matplotlib, Text API. Checked 2026-11-14.
- Plotly, Legends in Python. Checked 2026-11-14.
- Plotly, Python graphing library licensing and offline use. Checked 2026-11-14.
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.
| Control | Scope | Affected text or setting | Input | Caveat | Source reference |
|---|---|---|---|---|---|
| fontsize | Legend creation | Entry text | Numeric points or relative size name | Used only when prop is absent | pyplot.legend |
| prop | Legend creation | Entry font properties | Dictionary or FontProperties | Put size in this object when using it | pyplot.legend; Legend API |
| title_fontsize | Legend creation | Title text | Numeric points or relative size name | Do not combine with title_fontproperties | pyplot.legend |
| title_fontproperties | Legend creation | Title font properties | Dictionary or FontProperties | Put size here with other title font settings | pyplot.legend |
| legend.fontsize | Runtime defaults | New legend entry text | rcParams setting | Configure before constructing the legend | Customization guide; Legend API |
| legend.title_fontsize | Runtime defaults | New legend title text | rcParams setting | Explicit title arguments provide local control | Customization guide; pyplot.legend |
| get_texts() + set_fontsize() | Existing legend | Entry Text objects | Numeric points or relative size name | Iterate entry Text objects returned by get_texts | Legend API; Text API |
| get_title() + set_fontsize() | Existing legend | Title Text object | Numeric points or relative size name | Edit title Text separately from entries | Legend API; Text API |
| rc_context | Scoped defaults | Runtime configuration | Dictionary of rcParams | Restores changed rcParams on exit except backend | rc_context reference; Customization guide |
Sources
- Matplotlib pyplot.legend reference (accessed 2026-11-14)
- Matplotlib Legend API (accessed 2026-11-14)
- Matplotlib Text API (accessed 2026-11-14)
- Matplotlib customization guide (accessed 2026-11-14)
- Matplotlib rc_context reference (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







