Change the title and axis label font sizes in Matplotlib

Python

Matplotlib

Axes

Change title and label font sizes

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 labels distract from the visualization and make the plot less effective.

Generally, Matplotlib functions that create text elements accept a fontsize parameter, making it trivial to tweak fontsizes. However, to save some typing, consider globally changing the font size.

Code Example

Use the fontsize argument to plt.title(), plt.xlabel(), and plt.ylabel() to change the font size. fontsize can be a string or an integer value.

import matplotlib.pyplot as plt

# Adjust font sizes here
plt.title("My Title", fontsize='xx-large')
plt.xlabel("My 'X' Label", fontsize='large')
plt.ylabel("My 'Y' Label", fontsize='small')

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.

plt.title(), plt.xlabel(), and plt.ylabel() accept the Matplotlib Text properties as arguments.

More Examples

Specify an Absolute Font Size

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

# Specify font size in points here
plt.title("My Title", fontsize=30)
plt.xlabel("My 'X' Label", fontsize=12)
plt.ylabel("My 'Y' Label", fontsize=20)

plt.show()

png

Object Oriented Interface

Changing the font size with the object oriented interface is quite similar to the pyplot interface.

ax = plt.axes()

# Specify font size in points here
ax.set_title("My Title", fontsize=30)
ax.set_xlabel("My 'X' Label", fontsize=12)
ax.set_ylabel("My 'Y' Label", fontsize=20)

plt.show()

png

Change the Base Font Size

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