简体   繁体   中英

Legend for subplots

I have 4 subplots and I would like to keep only legend from one, since they are the same.

Example of dataset:

    P   M   PP  R   F A D
0   BO  NB  0.72    0.82    0.71    0.91    A
1   BO  LR  0.71    0.62    0.52    0.91    A
2   BO  SVM 0.85    0.64    0.76    0.92    A
3   BO  SGD 0.54    0.54    0.73    0.92    B
4   BO  RF  0.75    0.70    0.65    0.92    B

Attempt:

fig = plt.figure(figsize=(8,8))
for n, col in enumerate(['PP','R','F','A'], start=1):
    ax = plt.subplot(2,2,n)
    fig.subplots_adjust(hspace=.5)
    sns.lineplot(data=df, x='M', y=col, hue='P', style='D')
    plt.xticks(rotation=10)

fig.legend(bbox_to_anchor=(1.05, 1), loc=2)

This shows four legends plus one with all of them. I would like to keep only one (the most external one). How can I do it?

I am not sure if this can be done with sns.lineplot() , but you can get the same result using sns.relplot() :

import pandas as pd
import seaborn as sns

d = {'P': {0: 'BO', 1: 'BO', 2: 'BO', 3: 'BO', 4: 'BO'},
     'M': {0: 'NB', 1: 'LR', 2: 'SVM', 3: 'SGD', 4: 'RF'},
     'PP': {0: '0.72', 1: '0.71', 2: '0.85', 3: '0.54', 4: '0.75'},
     'R': {0: '0.82', 1: '0.62', 2: '0.64', 3: '0.54', 4: '0.70'},
     'F': {0: '0.71', 1: '0.52', 2: '0.76', 3: '0.73', 4: '0.65'},
     'A': {0: '0.91', 1: '0.91', 2: '0.92', 3: '0.92', 4: '0.92'},
     'D': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'}}


df = pd.DataFrame(d)
df2 = df.melt(['P', 'M', 'D'])
g = sns.relplot(data=df2, 
            x='M', 
            y="value", 
            hue='P', 
            style='D', 
            col="variable", 
            col_wrap=2,
            col_order = ['PP', 'R', 'F', 'A'],
            kind="line",
            facet_kws={'sharey': False, 'sharex': False},
            height=3,
           )
g._legend.set_bbox_to_anchor([0.9, 1])
g._legend._loc=2

This gives:

在此处输入图像描述

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