How to Change Legend Font Size in Matplotlib

  1. rcParams Method to Specify the Fontsize
  2. plt.legend(fontsize= ) Method to Specify Legend Fontsize
  3. prop Property in the Legend

We have different methods to set the font size of the text in the legend in Matplotlib.

rcParams Method to Specify the Fontsize

rcParams is a dictionary to handle Matplotlib properties and default styles in Matplotlib.

1. plt.rc('legend', fontsize= ) Method

fontsize could be the integer that has the unit of points, or a size string like

xx--small
x-small
small
medium
large
x-large
xx-large
plt.rc('legend', fontsize=16)
plt.rc('legend', fontsize='medium')

Matplotlib Legend Specify Font Size

2. plt.rcparams.update() Method

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x), label="sin(x)")

params = {'legend.fontsize': 16,
          'legend.handlelength': 3}

plt.rcParams.update(params)

plt.legend(loc='upper left')

plt.tight_layout()

plt.show()

legend.fontsize specifies the legend font size, and legend.handlelength specifies the length of the legend handles in font-size units.

plt.rcParams.update(params) updates the Matplotlib properties and styles with the dictionary params as defined above.

Or, you could update the rcParams dictionary by putting the key in the parentheses [],

plt.rcParams['legend.fontsize'] = 16
plt.rcParams['legend.handlelength'] = 16

plt.legend(fontsize= ) Method to Specify Legend Fontsize

plt.legend(fontsize=) could specify the legend font size for each legend when it is created.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x), label="sin(x)")

plt.legend(fontsize=16, loc='upper right')

plt.show()

prop Property in the Legend

prop property in the legend could set the individual font size of the legend. The value of prop is the dictionary of keywords from matplotlib.font_manager.FontProperties.

plt.legend(prop={'size': 16})

Example:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x), label="sin(x)")

plt.legend(prop={'size':16}, loc='best')

plt.show()

Related Article - Matplotlib Legend

  • How to Place Legend Outside of The Plot in Matplotlib
  • How to Create A Single Legend For All Subplots in Matplotlib
  • comments powered by Disqus