Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set font size of Matplotlib axis Legend?

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()

legend fontsize

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?

like image 324
Tapajit Dey Avatar asked Sep 13 '12 08:09

Tapajit Dey


People also ask

How do you change the font size in legend?

You can change the font size for a MATLAB legend by setting the 'FontSize' property of the Legend object. For example, plot four lines. Create a legend and assign the Legend object to the variable 'lgd'. Then, use dot notation to access the 'FontSize' property and set the value to 14 points.

How do I change the font size axis labels in Matplotlib?

If we want to change the font size of the axis labels, we can use the parameter “fontsize” and set it your desired number.

How do I change the axis size in Matplotlib?

To change the range of X and Y axes, we can use xlim() and ylim() methods.


3 Answers

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')

As of Matplotlib 3.0.3, you can also set it globally with

plt.rcParams['legend.title_fontsize'] = 'xx-small'
like image 55
nothilaryy Avatar answered Oct 19 '22 07:10

nothilaryy


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
like image 41
DougR Avatar answered Oct 19 '22 05:10

DougR


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})
like image 33
Max Avatar answered Oct 19 '22 05:10

Max