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.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')
7/20/2017 3:02:56 PM

Accepted Answer

You can set an individual font size for the legend by adjusting the prop keyword.

plot.legend(loc=2, prop={'size': 6})

This takes a dictionary of keywords corresponding to matplotlib.font_manager.FontProperties properties. See the documentation for legend:

Keyword arguments:

prop: [ None | FontProperties | dict ]
    A matplotlib.font_manager.FontProperties instance. If prop is a 
    dictionary, a new instance will be created with prop. If None, use
    rc settings.

It is also possible, as of version 1.2.1, to use the keyword fontsize.

7/20/2017 2:44:17 PM

This should do

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow