I\'m creating plots using Matplotlib that I save as SVG, export to .pdf + .pdf_tex using Inkscape, and include the .pdf_tex-file in a LaTeX document.
This means tha
You may use the bbox_to_anchor
and bbox_transform
parameters to help you setting the anchor for your legend:
ax = plt.gca()
plt.legend(bbox_to_anchor=(1.1, 1.1), bbox_transform=ax.transAxes)
Note that (1.1, 1.1)
are in the axes coordinates in this example. If you wish to use the data coordinates you have to use bbox_transform=ax.transData
instead.
You can move a legend after automatically placing it by drawing it, and then getting the bbox position. Here's an example:
import matplotlib.pyplot as plt
import numpy as np
# Plot data
x = np.linspace(0,1,100)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(221) #small subplot to show how the legend has moved.
# Create legend
plt.plot(x, y, label = '{\\footnotesize \$y = x^2\$}')
leg = plt.legend( loc = 'upper right')
plt.draw() # Draw the figure so you can find the positon of the legend.
# Get the bounding box of the original legend
bb = leg.get_bbox_to_anchor().inverse_transformed(ax.transAxes)
# Change to location of the legend.
xOffset = 1.5
bb.x0 += xOffset
bb.x1 += xOffset
leg.set_bbox_to_anchor(bb, transform = ax.transAxes)
# Update the plot
plt.show()