Question

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?

Was it helpful?

Solution

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")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top