How to set font size of Matplotlib axis Legend?

2019-01-16 18:42发布

问题:

I have a code like this:

import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('xx-small')
fig=plt.figure()
ax1=fig.add_subplot(111)
plot([1,2,3], label="test1")
ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
           prop = fontP,fancybox=True,shadow=False,title='LEGEND')
plt.show()

It can be seen in the plot that the setting in Fontsize does not affect the Legend Title font size.

How to set the font size of the legend title to a smaller size?

回答1:

This is definitely an old question, but was frustrating me too and none of the other answers changed the legend title fontsize at all, but instead just changed the rest of the text. So after banging my head against the matplotlib documentation for awhile I came up with this.

legend = ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
           prop = fontP,fancybox=True,shadow=False,title='LEGEND')

plt.setp(legend.get_title(),fontsize='xx-small')


回答2:

Here is how to change the fontsize of the legend list and/or legend title:

legend=plt.legend(list,loc=(1.05,0.05), title=r'$\bf{Title}$') #Legend: list, location, Title (in bold)
legend.get_title().set_fontsize('6') #legend 'Title' fontsize
plt.setp(plt.gca().get_legend().get_texts(), fontsize='12') #legend 'list' fontsize


回答3:

I don't know how to set it up for an individual plot, but I always do it globally:

plt.rc('legend',**{'fontsize':6})


回答4:

Banged my head against it too, here is another more flowing way of doing it:

leg = ax.legend()
leg.set_title('A great legend',prop={'size':14})


回答5:

This is the fastest:

plt.legend(loc=2,prop={'size':6})


回答6:

I generally do in this way. Once the plot has been done i do the following

plt.legend(loc=0, numpoints=1)
leg = plt.gca().get_legend()
ltext  = leg.get_texts()
plt.setp(ltext, fontsize='small') 

I don't know if this works for you