Search code examples
pythonmatplotlibseabornlegend

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?


Solution

  • 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')