Matplotlib legend fontsize

Question:

Am I using the fontsize argument incorrectly in the following code?
According to the documentation, this should be a valid keyword argument.

import pylab
pylab.plot(range(5), label='test')
pylab.legend(fontsize='small') 
pylab.show()

Traceback:

Traceback (most recent call last):
  File "test_label.py", line 6, in <module>
    pylab.legend(fontsize='small')
  File "C:swframepython-V01-01libsite-packagesmatplotlibpyplot.py", line 2
791, in legend
    ret =  gca().legend(*args, **kwargs)
  File "C:swframepython-V01-01libsite-packagesmatplotlibaxes.py", line 447
5, in legend
    self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'fontsize'

Python: 2.7, Matplotlib: 1.1.0

Edit: Note, I am not looking for alternative ways to set the font size. I want to know why this goes wrong.

Asked By: Dhara

||

Answers:

Try:

pylab.legend(prop={'fontsize': 'small'}) 

1.2.0 legend docs (the oldest I could find online)

Setting the font size via kwarg does not work because you are using an antiquated version of matplotlib. The error it is giving you, TypeError: __init__() got an unexpected keyword argument 'fontsize' means that fontsize is not a valid keyword argument of the __init__ function.

The functionality of passing in fontsize was added in this PR which was done between the 1.1.0 and 1.2.0 releases.

Answered By: tacaswell
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.