HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How to put the legend outside the plot

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howtheplotlegendoutsideput

Problem

I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced.

  • I want to keep the legend box outside the plot area (I want the legend to be outside at the right side of the plot area).



  • Is there a way to reduce the font size of the text inside the legend box, so that the size of the legend box will be small?

Solution


  • You can make the legend text smaller by specifying set_size of FontProperties.



  • Resources:



  • Legend guide



  • matplotlib.legend



  • matplotlib.pyplot.legend



  • matplotlib.font_manager



  • set_size(self, size)



  • Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, and None.



  • Real Python: Python Plotting With Matplotlib (Guide)



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

fontP = FontProperties()
fontP.set_size('xx-small')

p1, = plt.plot([1, 2, 3], label='Line 1')
p2, = plt.plot([3, 2, 1], label='Line 2')
plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', prop=fontP)


  • fontsize='xx-small' also works, without importing FontProperties.



plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', fontsize='xx-small')

Context

Stack Overflow Q#4700614, score: 204

Revisions (0)

No revisions yet.