0

I'm having trouble removing the original legend from Relplot. Since I want to change the text in the legend, I added some code to override the legend and now I want to get rid of the original one. However I can't write legend = False since, if so, it wouldn't give the added legend as well. Any suggestion?

    sns.relplot(data = df_R_subject1, x="CDL-07_CO2", y="CDL-07_Ta", size="freshair_S1",  hue="posture_S1",
            sizes=(200, 50), alpha=.5, palette="muted", height=6)


L = plt.legend(bbox_to_anchor = (1,0.35), frameon=False)
L.get_texts()[0].set_text('Posture')
L.get_texts()[1].set_text('Standing')
L.get_texts()[2].set_text('Sitting')

L.get_texts()[3].set_text('Do you need fresh air?')
L.get_texts()[4].set_text('Yes')
L.get_texts()[5].set_text('No change')

plt.ylabel("Air temperature (°C)", fontsize = 12)
plt.xlabel("CO2 concentration (ppm)", fontsize = 12)

plt.show()

Example plot: Example plot

How can I get rid of the legend (right side)?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Yunni
  • 15
  • 2
  • 2
    Can you provide a reproducible example (minimal dataset)? – mozway Sep 28 '22 at 09:03
  • code wise it's easiest to use [`df_R_subject1 = df_R_subject1.rename({'posture_S1': 'Posture', 'freshair_S1': 'Do you need fresh air?'}, axis=1)`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rename.html) to change the column names, which are passed to the seaborn parameters and used in the legend, and to use [`df_R_subject1['Posture'] = df_R_subject1['Posture'].map({10.0: 'Standing', 11.0: 'Sitting'})`](https://pandas.pydata.org/docs/reference/api/pandas.Series.map.html) to change the categorical values in the dataframe. – Trenton McKinney Sep 28 '22 at 15:23

1 Answers1

1

relplot is a figure-level function and when you use plt.legend(), this is causing a second legend to be created. You should be using L= g._legend instead. Full code below. Used tips data as no data was provided...

import seaborn as sns
import matplotlib.pyplot as plt
df_R_subject1 = sns.load_dataset("tips")
df_R_subject1.rename(columns={'total_bill': 'CDL-07_Ta', 'tip' : 'CDL-07_CO2', 'sex':'posture_S1', 'time':'freshair_S1'}, inplace=True)

g=sns.relplot(data = df_R_subject1, x="CDL-07_CO2", y="CDL-07_Ta", size="freshair_S1",  hue="posture_S1",
            sizes=(200, 50), alpha=.5, palette="muted")
L= g._legend
L.get_texts()[0].set_text('Posture')
L.get_texts()[1].set_text('Standing')
L.get_texts()[2].set_text('Sitting')

L.get_texts()[3].set_text('Do you need fresh air?')
L.get_texts()[4].set_text('Yes')
L.get_texts()[5].set_text('No change')

plt.ylabel("Air temperature (°C)", fontsize = 12)
plt.xlabel("CO2 concentration (ppm)", fontsize = 12)

plt.show()

enter image description here

Redox
  • 9,321
  • 5
  • 9
  • 26