Position Legends in Seaborn
import pandas as pd
import seaborn as sns
DATA_PATH = '../input/iris/Iris.csv'
df = pd.read_csv(DATA_PATH)
df.head(1)
Id | SepalLengthCm | SepalWidthCm | PetalLengthCm | PetalWidthCm | Species | |
---|---|---|---|---|---|---|
0 | 1 | 5.1 | 3.5 | 1.4 | 0.2 | Iris-setosa |
When working with Python and Seaborn (sns
) it's common to have plots in which the legend overlaps the plot content, we can see this issue in the below code output:
g = sns.scatterplot(x = 'SepalWidthCm', y = 'SepalLengthCm', hue = 'Species', data = df)
Using the g.legend
function of a graph we are able to move the legend to a more suitable location
g = sns.scatterplot(x = 'SepalWidthCm', y = 'SepalLengthCm', hue = 'Species', data = df)
g.legend(loc = 'center left', bbox_to_anchor = (1, 0.5), ncol = 1)
<matplotlib.legend.Legend at 0x7fc2034acb10>
You can find out more about how the
legend
function works in the Matplotlib Docs, and you can find an interactive version of this notebook on Kaggle