pythonseabornlegend

Specify the Position of the Legend Title / Variable Name with Legend on Top with Seaborn


When I move the legend of a Seaborn plot from its default position to the top of the plot, I want to have the variable (hue) name in the same row as the possible variable values.

Starting from this plot:

import seaborn as sns
penguins = sns.load_dataset("penguins")
ax = sns.relplot(penguins, x="bill_length_mm",y="flipper_length_mm" , hue="species")

Relplot with legend on the right

I want to move the legend on top of the plot(e.g. like this):

ax = sns.relplot(penguins, x="bill_length_mm",y="flipper_length_mm" , hue="species")
sns.move_legend(ax, "lower center", bbox_to_anchor=(.5, 1), ncol=4)

Relplot with the legend on top

But I want the variable name (species in the example) to be left of its values instead of on top of them. When also setting the style argument, this works fine(ignoring that the legend is to wide in this example):

ax = sns.relplot(penguins, x="bill_length_mm",y="flipper_length_mm" , hue="species", style="sex")
sns.move_legend(ax, "lower center", bbox_to_anchor=(.5, 1), ncol=7)

Relplot with legend using hue and style on top


Solution

  • You could retrieve the legend, get its bbox and move the title down/left. Here I used half of the width of the bbox to the left and a fixed extra left and down:

    import seaborn as sns
    
    penguins = sns.load_dataset('penguins')
    
    g = sns.relplot(penguins, x='bill_length_mm', y='flipper_length_mm', hue='species')
    
    sns.move_legend(g, 'lower center', bbox_to_anchor=(0.5, 1), ncol=7)
    bbox = g.legend.get_window_extent()
    g.legend.get_title().set_position((-bbox.width/2-20, -20))
    

    You might have to tweak a bit the fixed values (here 20/20), it's otherwise relatively stable to changes of the figure size. Here with 6x3 inches as an example:

    matplotlib move legend title