0

In the following code, I generate a scatterplot where the legend is manually placed:

#!/usr/bin/env python3

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

frame = frame = pd.DataFrame({"x": [1, 2, 3, 4], "y": [4, 3, 2, 1]})
ax = frame.plot.scatter(x="x", y="y", label="dots")
plt.savefig("dots.pdf")
for y in [0.6, 0.7, 0.8]:
    ax.legend(bbox_to_anchor=(0.5, y), bbox_transform=ax.transAxes)
    plt.savefig("dots_{}.png".format(y))

It looks like the legend does not obey the placement instructions when it would make it hide a point:

y=0.6 y=0.7 y=0.8

Is there a way to avoid this? I mean, how to really force the placement of the legend?

bli
  • 7,549
  • 7
  • 48
  • 94

1 Answers1

1

You may be interested in reading my answer to "How to put the legend out of the plot". While it handles the case of putting the legend outside of the plot, most of it is applicable to placing the legend just anywhere, including inside the plot.

Most imporantly, the legend position is determined by the loc parameter. If you do not specify this parameter in the call to legend(), matplotlib will try to place the legend whereever it thinks it's best, (default is loc ="best").

In case you want to place the legend at a certain position, you may specify the coordinates of its lower left corner to loc:

ax.legend(loc=(0.5, 0.6))

If you want to specify another corner of the legend to be at a certain position, you need to specify the corner with the loc argument and the position using bbox_to_anchor:

ax.legend(loc="upper right", bbox_to_anchor=(0.5, 0.6))
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • It works well, but I don't understand how this interacts with 'plt.tight_layout()': If I put the legend at the top (`ax.legend(bbox_to_anchor=(0, 1), bbox_transform=ax.transAxes, loc="lower left")`), the legend is partially eaten out. I thought `plt.tight_layout()` was meant to make everything fit in the image, and I observe the contrary. – bli Dec 08 '17 at 16:48
  • No, `tight_layout` will not take the legend into account. But the case you descibe is sufficiently covered in [the answer](https://stackoverflow.com/a/43439132/4124317) I linked to. – ImportanceOfBeingErnest Dec 08 '17 at 16:50