user12753698
user12753698

Reputation:

Change legend's title fontsize in matplotlib

I would like to change the fontsize of the title of my legend in matplotlib. Here's my first guess

import matplotlib.pyplot as plt
fig = plt.figure()
ax  = fig.gca()
ax.plot(range(10))
lg  = ax.legend(['test entry'],title='test')
lg.set_title(fontsize='large')
plt.show()

which produces the error

    File "test.py", line 6, in <module>
    lg.set_title(fontsize='large')
TypeError: set_title() got an unexpected keyword argument 'fontsize'

I also tried

lg  = ax.legend(['test entry'],title='test',title_fontsize='large')

which produces

    self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'title_fontsize'

Upvotes: 4

Views: 10096

Answers (1)

user12422058
user12422058

Reputation:

Depending on your Python and therefore matplotlib version you have to proceed differently. Your second code is working with the latest version (3.1.2 ). You're probably running on Python 2 with matplotlib2.2.4. As you can see in the API documentation for this version there is no keyword argument for changing the legend's title size. You need to proceed like so :

lg.set_title('title',prop={'size':'large'})

Matplotlib 2.2.4

With Python 2 version of matplotlib you're stuck with

plt.legend.set_title('title',prop={'size':'large'})

Matplotlib 3.x.x

In the latest versions you have many options as

plt.legend.set_title('title',prop={'size':'large'})

or

plt.legend(...,title='title',title_fontsize='large')

or

plt.rcParams['legend.title_fontsize'] = 'large'

if you want to change the font size globally.


Here are some similar questions for more information :

Upvotes: 9

Related Questions