python – How to change the font size on a matplotlib plot

python – How to change the font size on a matplotlib plot

From the matplotlib documentation,

font = {family : normal,
        weight : bold,
        size   : 22}

matplotlib.rc(font, **font)

This sets the font of all items to the font specified by the kwargs object, font.

Alternatively, you could also use the rcParams update method as suggested in this answer:

matplotlib.rcParams.update({font.size: 22})

or

import matplotlib.pyplot as plt
plt.rcParams.update({font.size: 22})

You can find a full list of available properties on the Customizing matplotlib page.

If you are a control freak like me, you may want to explicitly set all your font sizes:

import matplotlib.pyplot as plt

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12

plt.rc(font, size=SMALL_SIZE)          # controls default text sizes
plt.rc(axes, titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc(axes, labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc(xtick, labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc(ytick, labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc(legend, fontsize=SMALL_SIZE)    # legend fontsize
plt.rc(figure, titlesize=BIGGER_SIZE)  # fontsize of the figure title

Note that you can also set the sizes calling the rc method on matplotlib:

import matplotlib

SMALL_SIZE = 8
matplotlib.rc(font, size=SMALL_SIZE)
matplotlib.rc(axes, titlesize=SMALL_SIZE)

# and so on ...

python – How to change the font size on a matplotlib plot

If you want to change the fontsize for just a specific plot that has already been created, try this:

import matplotlib.pyplot as plt

ax = plt.subplot(111, xlabel=x, ylabel=y, title=title)
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
             ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(20)

Leave a Reply

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