Home > Back-end >  How to remove a legend part of a seaborn facetgrid
How to remove a legend part of a seaborn facetgrid

Time:01-01

In Matplotlib/seaborn I create a facetgrid with the relplot command where the data attribute use for therow parameter is also used for the style attribute. This leads to a legend with two parts. One part is redundant and I want to remove this redundant part of the legend.

Here the code:

df = pd.read_csv('data.csv')
# Dataframe df has columns 'size', 'pricepersize', 'date' and 'series'

g = sns.relplot(x='size',
                y='pricepersize',
                data=df,
                kind='line',
                hue='date',
                style='series',
                row='series',
                markers=True
                )

plt.show()

And here the resulting graph grid (with the part of the legend I want to remove marked up in green):

facetgrid  with redundant legend part

How can I get rid of the "series" part in the legend, but keep the style parameter set to the same data column as the row parameter?

CodePudding user response:

I guess the easiest way is to let sns create the legend (this is the default), remove it and re-generate a new one from the desired entries of the original legend.

import seaborn as sns

tips = sns.load_dataset("tips")
fg = sns.relplot(data=tips, x="total_bill", y="tip", hue="day", row="time", kind='line', style='time')

gives

enter image description here

then use

fg.legend.remove()
fg.fig.legend(handles=fg.legend.legendHandles[:5], loc=7)

to finally get

enter image description here

  • Related