How to change the size of axis labels in Matplotlib?
Matplotlib offers customization options for the plots. Let’s learn how to change the size of the axis labels in Matplotlib to enhance readability.
Before starting let’s draw a simple plot with matplotlib.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [9, 8, 7, 6, 5]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
plt.show()
Output

Change the size of axis labels using xlabel()
and ylabel()
We can change the size of axis labels is by using the fontsize parameter in thexlabel() and ylabel() functions. This method allows you to specify the font size directly when setting the labels.
Let’s consider the following example:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [9, 8, 7, 6, 5]
fig, ax = plt.subplots()
ax.plot(x, y)
ax.plot(x, y)
ax.set_xlabel('x-axis', fontsize = 25)
ax.set_ylabel('y-axis', fontsize = 20)
plt.show()
Output:

Resulting plot after adjusting axis label size in Matplotlib
Adjust Axis Label Size in Matplotlib using set_xlabel()
and set_ylabel()
For more control, especially after plotting, you can use set_xlabel() and set_ylabel() methods of the Axes object. These methods are perfect for setting or modifying the labels after your plot has already been created.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.plot(x, y)
plt.gca().set_xlabel('Custom X-Axis Label', fontsize=20)
plt.gca().set_ylabel('Custom Y-Axis Label', fontsize=20)
plt.show()
Output:

Resulting output after adjusting axis label size in Matplotlib
Changing Font Size Globally with rcParams
If you require consistent font sizes across multiple plots, adjusting the default settings with rcParams
can be an efficient approach. This method sets a global font size for all axis labels in your environment.
import matplotlib as mpl
import matplotlib.pyplot as plt
#set globally
mpl.rcParams['axes.labelsize'] = 20
x = [5, 10, 4, 2, 8]
y = [49, 50, 90, 43, 87]
# Create a plot
plt.plot(x, y)
# no need to specify fontsize here as it's globally set
plt.xlabel('Custom X-Axis Label')
plt.ylabel('Custom Y-Axis Label')
plt.show()
Output:

Resulting output after adjusting axis label size in Matplotlib
Adjusting the size of axis labels in Matplotlib can significantly improve the clarity and impact of your visualizations. Whether you need to present data to your team or use plots for detailed analysis, these methods ensure your charts are both informative and visually appealing.