Чтобы переместить легенду наружу с помощью Seaborn, вы можете попробовать следующие методы:
Метод 1: использование параметра bbox_to_anchorв plt.legend
import seaborn as sns
import matplotlib.pyplot as plt
# Generate a sample plot
sns.set( )
tips = sns.load_dataset("tips")
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="sex")
# Move the legend outside the plot
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
# Show the plot
plt.show()
Метод 2: использование plt.subplotsи ax.legend
import seaborn as sns
import matplotlib.pyplot as plt
# Generate a sample plot
sns.set( )
tips = sns.load_dataset("tips")
fig, ax = plt.subplots()
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="sex", ax=ax)
# Move the legend outside the plot
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
# Show the plot
plt.show()
Метод 3: использование plt.legendи fig.legend
import seaborn as sns
import matplotlib.pyplot as plt
# Generate a sample plot
sns.set( )
tips = sns.load_dataset("tips")
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="sex")
plt.gca().legend_.remove()
# Move the legend outside the plot
plt.legend(title="Sex", loc='center left', bbox_to_anchor=(1, 0.5))
# Show the plot
plt.show()
Метод 4. Использование plt.legendи plt.savefig
import seaborn as sns
import matplotlib.pyplot as plt
# Generate a sample plot
sns.set( )
tips = sns.load_dataset("tips")
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="sex")
# Move the legend outside the plot
plt.legend(title="Sex", loc='center left', bbox_to_anchor=(1, 0.5))
# Save the plot image
plt.savefig("plot.png", bbox_inches='tight')
# Show the plot
plt.show()