Reputation: 8184
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:
Is there a way to avoid this? I mean, how to really force the placement of the legend?
Upvotes: 0
Views: 105
Reputation: 339102
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))
Upvotes: 1