Change the legend font size in Matplotlib

Python

Matplotlib

Legend

Change font size

Luc B.

Python

Matplotlib

Font

When creating plots in Matplotlib, it is crucial that text elements are legible so plots are easy to understand. Excessively small or large legend text distracts from the visualization and makes the plot less effective, so legend fonts should be adjusted to maximize readability.

Code Example

Use the fontsize argument to plt.legend() to change the legend font size. fontsize can be a string or an integer value.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1)
plt.plot(x, x**2)
plt.plot(x, 1-x)

# Adjust the legend font size here
plt.legend(['Line 1', 'Line 2'], fontsize='xx-large')

plt.show()

png

Valid fontsize strings are:

'xx-small'
'x-small'
'small'
'medium'
'large'
'x-large'
'xx-large'

These sizes are relative to the base font size. Passing an integer to fontsize allows directly specifying the font size in points.

More Examples

Specify an Absolute Font Size

Passing an integer to fontsize allows directly specifying the font size in points.

plt.plot(x, x**2)
plt.plot(x, 1-x)

# Specify the legend font size in points
plt.legend(['Line 1', 'Line 2'], fontsize=40)

plt.show()

png

Change the Base Font Size

To avoid repeatedly specifying the font size, take a look at this article.