Changing the data for hue in a scatterplot created by Seaborn relplot does not update the legend

56 Views Asked by At

I have five columns in a pandas dataframe df: 'axis_1', 'axis_2', 'axis_3', 'axis_4', and 'axis_5'.

I create a scatter plot using Seaborn's relplot function as follows:

grid = sns.relplot(data=df[[axis_1, axis_2, axis_3]], x=axis_1, y=axis_2, hue=axis_3)

The result is a scatter plot as follows

enter image description here

Now I use map to redraw the scatter plot so that it uses 'axis_4' instead of 'axis_1' column and 'axis_5' instead of 'axis_3' column. That is, I changed the data for X and for HUE.

grid.map(sns.scatterplot, x=df[axis_4], y=df[axis_2], hue=df[axis_5])

It works perfectly as far as the graph is concerned, i.e. the points have changed and so have their colors, according to the new data. The new plot is:

enter image description here

There is a problem, anyway: the legend. Both the title and the colors and values of the legend have remained the same as before. The map function did not update the legend, and it is not easy to do this by hand because relplot uses its own algorithm to determine what the hue-based legend looks like, and it would have to be reused.

Am I facing a limitation of the Seaborn library or is there some way to tell map to also regenerate the legend in the correct way?

1

There are 1 best solutions below

0
Dario de Judicibus On

I did not find a solution yet, but I found a workaround and I wish to share it here, in case it could be useful to someone else.

First I moved the legend created by Seaburn out of sight, that is, outside the Tkinter canvas, by

sns.move_legend(grid, "upper center", bbox_to_anchor=(1, 2))

Then I created a mathplotlib legend. It looks like that legend replicates the legend already created by Seaburn. Note that, if I remove the Seaburn legend rather than moving it out of sight, the resulting mathplotlib legend is empty. That is why I move the original legend rather than removing it.

    plt.legend(
        title=<<<dynamic value based on hue data>>>,
        loc='center right',
        bbox_to_anchor=(1.16, 0.5)
    )

When I change the data in the scatter plot, also the title of the legend changes and the legend changes according to new hue data. By magic. :-)

The resulting chart now is:

enter image description here