3

I would like to plot two dataframes with a 'long' representation, and differing axis, to one plot using sns.lineplot(). Yet, I am failing plot it with a single legend containing the elements of both lineplots.

The issue is similar to this: Secondary axis with twinx(): how to add to legend?, though I'd like to use seaborn.

A minimal working example up to the point I got stuck is given below.

import pandas as pd
import seaborn as sns
import numpy as np
import itertools

# mock dataset
lst = range(1,11)
steps1 = list(itertools.chain.from_iterable(itertools.repeat(x, 4) for x in lst))

labels1 = ['A','B']*20
values1 = list(np.random.uniform(0,1,40))
df1 = pd.DataFrame({'steps':steps1, 'lab':labels1, 'vals':values1})

lst = range(6,11)
steps2 = list(itertools.chain.from_iterable(itertools.repeat(x, 4) for x in lst))

labels2 = ['C','D']*10
values2 = list(np.random.uniform(10,20,20))
df2 = pd.DataFrame({'steps':steps2, 'lab2':labels2, 'others':values2})


# plotting
fig, ax = plt.subplots()
fig = sns.lineplot(x='steps',y='vals', data=df1, hue='lab',palette='bright', legend='brief')   

ax2 = ax.twinx()
fig2 = sns.lineplot(x='steps',y='others', hue='lab2', data=df2 ,palette='dark', legend='brief')    

# How do I merge the legends into one?
# the solution below gives me one merged and one separate legend

h1,l1 = fig.get_legend_handles_labels()
h2,l2 = fig2.get_legend_handles_labels()
ax.legend(loc=3, handles=h1+h2, labels = l1+l2)

skna.1000
  • 51
  • 8

1 Answers1

2

I just resolved it by removing the obsolete legend by ax2.get_legend().remove().

skna.1000
  • 51
  • 8
  • 2
    This will remove one of the legends. What if they are different types of plots and you want to merge the legends? For example barplot and line plot. – pooria May 12 '22 at 19:00