简体   繁体   中英

How to remove a legend part of a seaborn facetgrid

In Matplotlib/seaborn I create a facetgrid with the relplot command where the data attribute use for the row 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

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?

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

在此处输入图像描述

then use

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

to finally get

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM