4

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?

Laxsnor
  • 857
  • 1
  • 12
  • 21

1 Answers1

5

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.

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • So this works... kind of. The legend box stays a fixed width, but it now seems to have problems overlaying two captions. e.g.: http://i.imgur.com/RYemFRs.png – Laxsnor Dec 08 '16 at 03:15
  • This is indeed very strange. I do not see how this can be solemnly related to setting the bounding box of the legend. I would guess that this issue is related to the rest of the code and in order to solve it, one would need to create a [MCVE]. – ImportanceOfBeingErnest Dec 08 '16 at 07:21
  • The drawback of this solution is that one needs to provide the width of the legend relative to the width of the axis. It would be helpful to be able to specify the width of the legend in absolute terms. – Bastian Feb 17 '21 at 14:02