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

Patricia Arquette
Release: 2024-10-25 04:43:29
Original
1021 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template