Laxsnor
Laxsnor

Reputation: 857

Fix size of legend in matplotlib

I am trying to make automated plots with matplotlib, with several different features plotted on top of one another (the background is a filled contour plot, one level above is a pcolormesh). The topmost feature that I'm trying to plot is several scatter plots, with different labels and icons.

I'm trying to add a legend to this plot, currently using the following commands:

leg = ax.legend(legplots,
           legnames,
           scatterpoints=1,
           loc='upper center',
           ncol=3,
           fontsize=14,
         bbox_to_anchor=(0.5, -0.14),
          fancybox=True, shadow=True)

Assume that ax is the main axes, and that legplots and legnames are lists of scatter plots and their appropriate labels respectively.

Adding the legend works correctly, but as the number of legplots that I have (and their name lengths) vary, as you animate the plots, the legend grows and shrinks in size. How do I control the size of the legend box and the column widths inside the legend? Is this possible?

Upvotes: 4

Views: 6492

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339660

At the moment your bounding box has a size of 0, since you only specify its position ((0.5, -0.14)).

You can set the bounding box of the legend to be bigger than 0 and also big enough for the maximum size that it needs to have for the maximum number of elements to fit in. I think you will need to find that size by trial and error.

So using the full 4-tuple notation

bbox_to_anchor=(x0, y0, width, height)

in conjunction with an appropriate loc parameter and the keyword argument mode="expand" will allow you to make the legend big enough for your needs. For a more detailed explanation about the 4-tuple notation see this post and also look at the legend location guide.

Upvotes: 5

Related Questions