user5182786
user5182786

Reputation:

How to anchor top right corner of Legend to top right corner of Axes in matplotlib?

I'm trying to position the legend of a matplotlib figure exactly up in the top right corner of the axes, so that there are no tiny line sections between the edges of the legend and the edges of the axes. I'd like to do it by calling methods of a Legend object directly, like Legend.set_bbox_to_anchor(), but my attempts don't seem to move the legend at all.

Here's my most recent try:

leg.set_bbox_to_anchor((1,1), transform = ax.transAxes)

where leg is the Legend object and ax is the parent Axes object. Do You have any ideas how can I achieve this?

Upvotes: 0

Views: 6534

Answers (2)

theo olsthoorn
theo olsthoorn

Reputation: 501

Here is a simple example of how to finetune the position of the legend:

# Get legend
leg = ax.legend(loc='lower left')
# Reposition it using axes relative coordinates (0...1, 0...1)
leg.set_bbox_to_anchor((0.250, 0.11, 0.3, 0.5), transform=ax.transAxes)

Upvotes: 0

Tony Babarino
Tony Babarino

Reputation: 3405

Try plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0).

Upvotes: 6

Related Questions