+2 votes
in Programming Languages by (73.8k points)

The default font size of legends in matplotlib plots is very small. I want to change the font size of legends. How can I do it?

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

The simplest way to change the font size is:

ax1.legend(loc='upper left', prop={'size': 14}), where 14 is the font size

Have a look at the following code to understand how to use legend(). The codes in bold are for displaying legends and changing their font size.

fig, ax1 = plt.subplots()

title = 'My test plot'

plt.title('\n'.join(wrap(title,60)), fontsize=18)

t = [i for i in range(len(x))]

ax1.bar(t, y1, color='r', label='test value')

ax1.set_xlabel('Range', fontsize=16)

ax1.set_ylabel('\n'.join(wrap('Percentage', 40)) , color='r', fontsize=16)

ax1.tick_params('y', colors='r')

ax1.tick_params('x', which='minor', bottom=False, top=False)

ax1.minorticks_on()

# ask matplotlib for the plotted objects and their labels

lines1, labels1 = ax1.get_legend_handles_labels()

ax1.legend(lines1, labels1, loc='upper left', prop={'size': 14})

fig.tight_layout()

plt.show() 


...