[python] How to change legend size with matplotlib.pyplot

Simple question here: I'm trying to get the size of my legend using matplotlib.pyplot to be smaller (i.e., the text to be smaller). The code I'm using goes something like this:

plot.figure()
plot.scatter(k, sum_cf, color='black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0],  color='b', label='Dis 1: cf = .6, var = .2')
plot.scatter(k, data[:, 1],  color='r',  label='Dis 2: cf = .2, var = .1')
plot.scatter(k, data[:, 2],  color='g', label='Dis 3: cf = .1, var = .01')
plot.legend(loc=2)

This question is related to python size matplotlib legend

The answer is


On my install, FontProperties only changes the text size, but it's still too large and spaced out. I found a parameter in pyplot.rcParams: legend.labelspacing, which I'm guessing is set to a fraction of the font size. I've changed it with

pyplot.rcParams.update({'legend.labelspacing':0.25})

I'm not sure how to specify it to the pyplot.legend function - passing

prop={'labelspacing':0.25}

or

prop={'legend.labelspacing':0.25}

comes back with an error.


you can reduce the legend size setting:

plt.legend(labelspacing=y, handletextpad=x,fontsize)  

labelspacing is the vertical space between each label.

handletextpad is the distance between the actual legend and your label.

And fontsize is self-explanatory


This should do

import pylab as plot
params = {'legend.fontsize': 20,
          'legend.handlelength': 2}
plot.rcParams.update(params)

Then do the plot afterwards.

There are a ton of other rcParams, they can also be set in the matplotlibrc file.

Also presumably you can change it passing a matplotlib.font_manager.FontProperties instance but this I don't know how to do. --> see Yann's answer.


Now in 2020, with matplotlib 3.2.2 you can set your legend fonts with

plt.legend(title="My Title", fontsize=10, title_fontsize=15)

where fontsize is the font size of the items in legend and title_fontsize is the font size of the legend title. More information in matplotlib documentation


There are multiple settings for adjusting the legend size. The two I find most useful are:

  • labelspacing: which sets the spacing between label entries in multiples of the font size. For instance with a 10 point font, legend(..., labelspacing=0.2) will reduce the spacing between entries to 2 points. The default on my install is about 0.5.
  • prop: which allows full control of the font size, etc. You can set an 8 point font using legend(..., prop={'size':8}). The default on my install is about 14 points.

In addition, the legend documentation lists a number of other padding and spacing parameters including: borderpad, handlelength, handletextpad, borderaxespad, and columnspacing. These all follow the same form as labelspacing and area also in multiples of fontsize.

These values can also be set as the defaults for all figures using the matplotlibrc file.


using import matplotlib.pyplot as plt

Method 1: specify the fontsize when calling legend (repetitive)

plt.legend(fontsize=20) # using a size in points
plt.legend(fontsize="x-large") # using a named size

With this method you can set the fontsize for each legend at creation (allowing you to have multiple legends with different fontsizes). However, you will have to type everything manually each time you create a legend.

(Note: @Mathias711 listed the available named fontsizes in his answer)

Method 2: specify the fontsize in rcParams (convenient)

plt.rc('legend',fontsize=20) # using a size in points
plt.rc('legend',fontsize='medium') # using a named size

With this method you set the default legend fontsize, and all legends will automatically use that unless you specify otherwise using method 1. This means you can set your legend fontsize at the beginning of your code, and not worry about setting it for each individual legend.

If you use a named size e.g. 'medium', then the legend text will scale with the global font.size in rcParams. To change font.size use plt.rc(font.size='medium')


There are also a few named fontsizes, apart from the size in points:

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

Usage:

pyplot.legend(loc=2, fontsize = 'x-small')

plot.legend(loc = 'lower right', decimal_places = 2, fontsize = '11', title = 'Hey there', title_fontsize = '20')


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to size

PySpark 2.0 The size or shape of a DataFrame How to set label size in Bootstrap How to create a DataFrame of random integers with Pandas? How to split large text file in windows? How can I get the size of an std::vector as an int? How to load specific image from assets with Swift How to find integer array size in java Fit website background image to screen size How to set text size in a button in html How to change font size in html?

Examples related to matplotlib

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm How to increase image size of pandas.DataFrame.plot in jupyter notebook? How to create a stacked bar chart for my DataFrame using seaborn? How to display multiple images in one figure correctly? Edit seaborn legend How to hide axes and gridlines in Matplotlib (python) How to set x axis values in matplotlib python? How to specify legend position in matplotlib in graph coordinates Python "TypeError: unhashable type: 'slice'" for encoding categorical data Seaborn Barplot - Displaying Values

Examples related to legend

Edit seaborn legend Remove legend ggplot 2.2 Reduce size of legend area in barplot Matplotlib scatter plot legend matplotlib: colorbars and its text labels Add a common Legend for combined ggplots Is there a way to change the spacing between legend items in ggplot2? Add legend to ggplot2 line plot plot legends without border and with white background Moving matplotlib legend outside of the axis makes it cutoff by the figure box