14
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
sns.set(style="darkgrid")

g = sns.scatterplot(x="Area", y="Rent/Sqft", hue="region", style="availability", data=df)

When I run this I get the below plot.

enter image description here

I want to move the legend outside of plot. I googled and tried the following

g.legend(loc='right', bbox_to_anchor=(1.25, 0.5), ncol=1)
plt.show()

But I don't get any output. Moreover, I can't understand how the object plt is connected to my sns object

I am using Jupyter Notebook, Python 3.6 and Seaborn 0.9.0.

Community
  • 1
  • 1
Vinay
  • 1,149
  • 3
  • 16
  • 28
  • Maybe you would rather use `ax.legend(loc='center left', bbox_to_anchor=(1.02, 0.5), ncol=1)`, but appart it works fine for me. Can you explain in more detail what "But I don't get any output." means? – ImportanceOfBeingErnest Dec 11 '18 at 23:32

1 Answers1

39

Please try the following:

g.legend(loc='center left', bbox_to_anchor=(1.25, 0.5), ncol=1)

You can change the first number to negative to put your legend on the left side if you want.

If you're using Jupyter IDE, you need to put both lines of your code in the same cell and run them together to get the output. In addition, there is no such thing as sns object. Most of the functions in seaborn return a matplotlib Axes object where you can use all the methods associated with the Axes object, like the one (i.e., .legend()) you are using here.

steven
  • 2,130
  • 19
  • 38
  • 2
    If you don't specify `loc`, it will be `"best"`, making the position unpredictable. In turn this means you should **always** use `loc` for non-automatic placements. Did you read my comment below the question? – ImportanceOfBeingErnest Dec 12 '18 at 08:32
  • 'best' is the default setting indeed, but I think it is unpredictable when you don't pass anything in `bbox_to_anchor`. – steven Dec 12 '18 at 17:33
  • 1
    It is always unpredictable, independent on whether you use the default axes bbox or supply your custom box. – ImportanceOfBeingErnest Dec 12 '18 at 19:58
  • Is there any reference? I'm interested in it. – steven Dec 12 '18 at 20:02
  • The [legend documentation](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html) states that `loc="best"` is default. What "best" is, would depend on the data in the axes, but if the legend is outside of the axes, it can become anything; meaning in this case the lower left corner could be at `(1.25, 0.5)` but if you're unlucky, its the upper right corner that is at that position. Hence, one should specify `loc` to be sure it is the corner of desire. I guess [this](https://stackoverflow.com/a/43439132/4124317) is a useful read. – ImportanceOfBeingErnest Dec 12 '18 at 20:14
  • Also [this question](https://stackoverflow.com/questions/39803385/what-does-a-4-element-tuple-argument-for-bbox-to-anchor-mean-in-matplotlib) provides more details. – ImportanceOfBeingErnest Dec 12 '18 at 20:17