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

1

11

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?

Jodhpur answered 16/2, 2012 at 0:30 Comment(0)
T
13

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")
Theresita answered 16/2, 2012 at 1:0 Comment(4)
Unfortunately, this does not work as it resets the legend location and label font sizes as well.Jodhpur
This is just a example that shows how to change label spacing. you should set legend location and font size by other parameters of legend().Theresita
Yes, I understand. However, a legend has already been created and using legend() requires that I reestablish ALL the parameters that I don't necessarily want to change.Jodhpur
You can save all the parameters in a dict params, and call legend(**prams), I updated the answer by using this method.Theresita

© 2022 - 2024 — McMap. All rights reserved.