How can I change the legend font size in Matplotlib?

Matplotlib is a popular Python library used for creating high-quality visualizations and plots. One common question that arises while using Matplotlib is how to change the legend font size. The legend is a key element in a plot that explains the different elements present in the plot. By default, the legend font size in Matplotlib is set to a standard size. However, users may want to customize the font size according to their preference or for better visualization. To change the legend font size in Matplotlib, one can use the “fontsize” parameter while creating the legend. This parameter allows the user to specify the font size in points. Alternatively, one can also use the “prop” parameter and pass a dictionary with the desired font properties, such as font size, to change the legend font size. This simple adjustment can greatly improve the overall appearance of a plot and make it more visually appealing.

Change Legend Font Size in Matplotlib


You can easily add a plot to a Matplotlib plot by using the following code:

import matplotlib.pyplotas plt

#add legend to plot
plt.legend()

And you can easily change the font size of the text in the legend by using one of the following methods:

Method 1: Specify a Size in Numbers

You can specify font size by using a number:

plt.legend(fontsize=18)

Method 2: Specify a Size in Strings

You can also specify font size by using strings:

plt.legend(fontsize="small")

Options include:

  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large

The following examples show how to use each of these methods in practice:

Example 1: Specify Font Size Using a Number

The following example shows how to specify a legend font size using a number:

import matplotlib.pyplotas plt

#create data
plt.plot([2, 4, 6, 11], label="First Line")
plt.plot([1, 4, 5, 9], label="Second Line")

#add legend
plt.legend(fontsize=18)

#show plot
plt.show()

Change legend font size in Matplotlib

Example 2: Specify Font Size Using a String

import matplotlib.pyplotas plt

#create data
plt.plot([2, 4, 6, 11], label="First Line")
plt.plot([1, 4, 5, 9], label="Second Line")

#add legend
plt.legend(fontsize="small")

#show plot
plt.show()

Change font size of legend in Matplotlib Plot in Python

Additional Resources

How to Change Font Sizes on a Matplotlib Plot
How to Add Text to Matplotlib Plots

x