Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move seaborn plot legend to a different position

I'm using factorplot(kind="bar") with seaborn.

The plot is fine except the legend is misplaced: too much to the right, text goes out of the plot's shaded area.

How do I make seaborn place the legend somewhere else, such as in top-left instead of middle-right?

like image 847
user124114 Avatar asked Nov 19 '14 14:11

user124114


People also ask

How do you make a legend outside the plot in Seaborn?

You can use plt. legend() to control legend properties directly through matplotlib , in accordance with Matplotlib Legend Guide. Note that in Seaborn 0.10. 0 tsplot was removed, and you may replicate (with different values for the estimation if you please) the plots with lineplot instead of tsplot .

How do I move the legend outside plot in Matplotlib?

In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.


1 Answers

Building on @user308827's answer: you can use legend=False in factorplot and specify the legend through matplotlib:

import seaborn as sns import matplotlib.pyplot as plt sns.set(style="whitegrid")  titanic = sns.load_dataset("titanic")  g = sns.factorplot("class", "survived", "sex",                    data=titanic, kind="bar",                    size=6, palette="muted",                    legend=False) g.despine(left=True) plt.legend(loc='upper left') g.set_ylabels("survival probability") 
  • plt acts on the current axes. To get axes from a FacetGrid use fig.
    • g.fig.get_axes()[0].legend(loc='lower left')
like image 88
Jules Avatar answered Sep 24 '22 09:09

Jules