How to change the font size on a matplotlib plot

There are a couple of ways to change the font size on a matplotlib plot. One way is to use the rcParams dictionary to set the font size for all text on the plot. Here's an example:

import matplotlib.pyplot as plt
import matplotlib as mpl

# Set the font size for all text on the plot
mpl.rcParams['font.size'] = 20

# Create a sample plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.show()

In this example, the font size for all text on the plot will be set to 20.

Watch a course Python - The Practical Guide

Another way to change the font size is to use the fontsize parameter when adding text to the plot, such as when adding a title or axis labels. Here's an example:

import matplotlib.pyplot as plt

# Create a sample plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)

# Add a title with a specific font size
plt.title("My Plot", fontsize=30)

# Add axis labels with a specific font size
plt.xlabel("X-axis", fontsize=20)
plt.ylabel("Y-axis", fontsize=20)

plt.show()

In this example, the title will have a font size of 30 and the axis labels will have a font size of 20.

You can also use plt.xticks(fontsize=) and plt.yticks(fontsize=) for controlling tick label fontsize.

You can also use rc function of matplotlib to set the font size of a group of element such as axes, tick, etc in a single go.

mpl.rc('axes', labelsize=20, titlesize=20)
mpl.rc('xtick', labelsize=15)
mpl.rc('ytick', labelsize=15)

It's also worth noting that you can specify the font family along with the size if you want to change the font itself. You can set the font for the entire plot or for individual text elements using the fontname parameter.

For example:

mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'Helvetica'

You can also specify 'serif' or 'monospace' as well.