How to Change Fonts in Matplotlib (With Examples)


You can use one of the following methods to change the font family in Matplotlib:

Method 1: Change Font for All Text

import matplotlib

matplotlib.rcParams['font.family'] = 'monospace'

Method 2: Change Font for Title & Axis Labels

import matplotlib.pylot as plt

mono_font = {'fontname':'monospace'}
serif_font = {'fontname':'serif'}

plt.title('Title of Plot',**mono_font)
plt.xlabel('X Label', **serif_font)

The following examples show how to use each method in practice.

Method 1: Change Font for All Text

The following code shows how to change the font family for all text in a Matplotlib plot:

import matplotlib
import matplotlib.pyplot as plt

#define font family to use for all text
matplotlib.rcParams['font.family'] = 'monospace'

#define x and y
x = [1, 4, 10]
y = [5, 9, 27]

#create line plot
plt.plot(x, y)

#add title and axis labels
plt.title('Title of Plot')
plt.xlabel('X Label')
plt.ylabel('Y Label')

#display plot
plt.show()

Notice that the title and both axis labels have a ‘monospace’ font, since that is the font family we specified in the rcParams argument.

Method 2: Change Font for Title & Axis Labels

The following code shows how to specify a unique font family for both the title and the axis labels:

import matplotlib.pyplot as plt

#define font families to use
mono_font = {'fontname':'monospace'}
serif_font = {'fontname':'serif'}

#define x and y
x = [1, 4, 10]
y = [5, 9, 27]

#create plot of x and y
plt.plot(x, y)

#specify title and axis labels with custom font families
plt.title('Title of Plot', **mono_font)
plt.xlabel('X Label', **serif_font)
plt.ylabel('Y Label', **serif_font)

#display plot
plt.show()

Notice that the title uses a ‘monospace’ font family while the x-axis and y-axis labels use a ‘serif’ font family.

Note: You can find a complete list of available font families that you can use in Matplotlib here.

Additional Resources

The following tutorials explain how to perform other common operations in Matplotlib:

How to Change Font Sizes on a Matplotlib Plot
How to Change Legend Font Size in Matplotlib
How to Set Tick Labels Font Size in Matplotlib

Leave a Reply

Your email address will not be published. Required fields are marked *