Nico Schlömer
Nico Schlömer

Reputation: 58891

align legend with axes

One recurring annoyance for me is trying to lign up matplotlib legends with the axes. To put them in the top right outside of the plot, it's usually recommended to do

plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")

like

import numpy
import matplotlib.pyplot as plt


x = numpy.linspace(-2, 2, 100)
y = x ** 2
plt.plot(x, y, "-", label="x**2")

plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
plt.grid()
# plt.show()
plt.savefig("out.png", transparent=True)

This leaves a gap, though:

enter image description here

Fiddling around with the magic values, e.g., bbox_to_anchor=(1.04, 1.015), does move the legend up and down, but if you finally got it somewhat right after a thousand attempts, it's all messed up after resizing the figure.

Any hints on how to do this better?

Upvotes: 1

Views: 178

Answers (1)

Sheldore
Sheldore

Reputation: 39072

You can achieve the desired alignment by using borderaxespad=0 while specifying the legend.


Complete code

import numpy
import matplotlib.pyplot as plt

x = numpy.linspace(-2, 2, 100)
y = x ** 2
plt.plot(x, y, "-", label="x**2")

plt.legend(bbox_to_anchor=(1.04, 1), borderaxespad=0) # <--- Here
plt.grid()

enter image description here

Upvotes: 1

Related Questions