0

I'm trying to place a legend just above the ax in matplotlib using ax.legend(loc=(0, 1.1)); however, if I change the figure size from (5,5) to (5,10) the legend shows up at a different distance from the top edge of the plot.

Is there any way to reference the top edge of the plot and offset it a set distance from it?

Thanks

Samesand
  • 101
  • 1
  • 5

1 Answers1

1

There is a constant distance between the legend bounding box and the axes by default. This is set via the borderaxespad parameter. This defaults to the rc value of rcParams["legend.borderaxespad"], which is usually set to 0.5 (in units of the fontsize).

So essentially you get the behaviour you're asking for for free. Mind however that you should specify the loc to the corner of the legend from which that padding is to be taken. I.e.

import numpy as np
import matplotlib.pyplot as plt

for figsize in [(5,4), (5,9)]:
    fig, ax = plt.subplots(figsize=figsize)
    ax.plot([1,2,3], label="label")

    ax.legend(loc="lower left", bbox_to_anchor=(0,1))

plt.show()

enter image description here

For more detailed explanations on how to position legend outside the axes, see How to put the legend out of the plot. Also relevant: How to specify legend position in matplotlib in graph coordinates

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712