How to edit a seaborn legend title and labels for figure-level functions
Took me a while to read through the above. This was the answer for me:
import seaborn as snsimport matplotlib.pyplot as plttips = sns.load_dataset("tips")g = sns.lmplot( x="total_bill", y="tip", hue="smoker", data=tips, legend=False)plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])plt.show(g)
Reference this for more arguments: matplotlib.pyplot.legend
- If
legend_out
is set toTrue
then legend is available through theg._legend
property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts. - Tested in
python 3.8.11
,matplotlib 3.4.3
,seaborn 0.11.2
import seaborn as sns# load the tips datasettips = sns.load_dataset("tips")# plotg = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': True})# titlenew_title = 'My title'g._legend.set_title(new_title)# replace labelsnew_labels = ['label 1', 'label 2']for t, l in zip(g._legend.texts, new_labels): t.set_text(l)
Another situation if legend_out
is set to False
. You have to define which axes has a legend (in below example this is axis number 0):
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': False})# check axes and find which is have legendleg = g.axes.flat[0].get_legend()new_title = 'My title'leg.set_title(new_title)new_labels = ['label 1', 'label 2']for t, l in zip(leg.texts, new_labels): t.set_text(l)
Moreover you may combine both situations and use this code:
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips, markers=["o", "x"], facet_kws={'legend_out': True})# check axes and find which is have legendfor ax in g.axes.flat: leg = g.axes.flat[0].get_legend() if not leg is None: break# or legend may be on a figureif leg is None: leg = g._legend# change legend textsnew_title = 'My title'leg.set_title(new_title)new_labels = ['label 1', 'label 2']for t, l in zip(leg.texts, new_labels): t.set_text(l)
This code works for any seaborn plot which is based on Grid
class.