Home >Backend Development >Python Tutorial >How to Move the Legend in Seaborn\'s Factorplot?

How to Move the Legend in Seaborn\'s Factorplot?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 04:43:291026browse

How to Move the Legend in Seaborn's Factorplot?

Customizing Seaborn Legend Placement

In seaborn's factorplot(kind="bar"), the legend's location is often not ideal, especially when the plot's elements are crowded. This article explores how to move the legend to a more suitable position, such as the top-left corner.

One approach is to prevent seaborn from generating the legend by setting legend=False. Subsequently, you can manually create the legend using matplotlib:

<code class="python">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")</code>

Note: To interact with the FacetGrid's axes from matplotlib, use fig.get_axes()[0]. For instance:

<code class="python">g.fig.get_axes()[0].legend(loc='lower left')</code>

The above is the detailed content of How to Move the Legend in Seaborn\'s Factorplot?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn