Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update the legend label spacing after legend font size is changed in matplotlib?

I'm writing a script that saves a figure with multiple formatting styles among which is the font size of legend text.

The legend.labelspacing in rcparams or the matplotlibrc file specifies the label spacing in fractions of the font size, so I might expect the actual spacing to change if the font size is changed. However, since the actual spacing is probably calculated when the legend is first created, any subsequent change to the font size of existing legend text objects has no effect on the label spacing. Is there a way to update the legend label spacing after an existing legend label object's font size has been changed? In summary here's is what I would like to do:

  1. plot something with a legend
  2. save the figure (format according to rcparams or matplotlibrc file)
  3. change several formatting properties (line widths, font sizes, etc.)
  4. save the figure again with the updated formatting properties, including re-adjusted legend label spacing

Is there a way to do this without changing the rcparams and then rebuilding the figure?

like image 333
mrclary Avatar asked Feb 16 '12 00:02

mrclary


People also ask

How do I change the font size on my legend in Matplotlib?

The prop keyword is used to change the font size property. It is used in Matplotlib as Using a prop keyword for changing the font size in legend.


1 Answers

Just call legend() with labelspacing parameter, here is an example:

import pylab as pl

pl.plot([0,1],[0,1], label="a")
pl.plot([0,2],[0,2], label="b")

pl.legend()
pl.savefig("p1.png")
pl.legend(labelspacing=2)
pl.savefig("p2.png")

To reuse parameters:

import pylab as pl

pl.plot([0,1],[0,1], label="a")
pl.plot([0,2],[0,2], label="b")
params = dict(loc="right", prop=dict(size=9))
pl.legend(**params)
pl.savefig("p1.png")
params["labelspacing"] = 2
pl.legend(**params)
pl.savefig("p2.png")
like image 111
HYRY Avatar answered Oct 19 '22 07:10

HYRY