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!