Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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. Kindly help me with the following queries:

  1. 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).

  2. Is there any way that I reduce the font size of the text inside the legend box, so that the size of the legend box will be small.

1 Answer

0 votes
by (106k points)

There are many ways to put the legend out of the plot:-

But the most important thing you can do is use the bbox_to_anchor keyword argument to place the legend partially outside the axes and/or decrease the font size.

bbox_to_anchor:-

This keyword gives a great degree of control for manual legend placement. For example, if you want your axes legend located at the figure’s top right-hand corner instead of the axes’ corner, simply specify the corner’s location and the coordinate system of that location. Then you can use the following piece of code.

plt.legend(bbox_to_anchor=(1, 1),

           bbox_transform=plt.gcf().transFigure)

An example that illustrates how we use bbox_to_anchor to put the legend out of the plot:-

import matplotlib.pyplot as plt 

import numpy as np 

fig = plt.figure() 

ax = plt.subplot(111) 

for i in xrange(5): 

    ax.plot(x, i * x, label='$y = %ix$' % i) 

ax.legend(bbox_to_anchor=(1.1, 1.05))

plt.show()

Related questions

0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
+1 vote
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...