Editar A Lenda do seaborn

Usando uma moldura de dados e este código em Python, fui capaz de criar um gráfico:

g = sns.lmplot('credibility', 'percentWatched', data=data, hue = 'millennial', markers = ["+", "."], x_jitter = True, y_jitter = True, size=5)
g.set(xlabel = 'Credibility Ranking\n ← Low       High  →', ylabel = 'Percent of Video Watched [%]')

enter image description here

{[[2]} no entanto, tendo a legenda dizer "+ 0 "e". 1 " não é muito útil para os leitores. Como posso editar os rótulos das lendas? Idealmente, em vez de dizer "milenar", diria "geração" e "+ milenar"". Gerações Mais Velhas "

Author: Serenity, 2017-07-20

1 answers

Se {[3] } está definido para {[4] } então a legenda está disponível pensa g._legend propriedade e é uma parte de uma figura. A lenda de Seaborn é um objeto padrão de lenda de matplotlib. Portanto, você pode mudar textos de legenda como:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

sns.plt.show()

enter image description here

Outra situação se legend_out estiver programada para False. Você tem que definir quais eixos tem uma legenda (em baixo exemplo Este é o número do eixo 0):

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = False)

# check axes and find which is have legend
leg = 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)
sns.plt.show()

enter image description here

Além disso, pode combinar ambas as situações e utilizar este código:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
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)

sns.plt.show()
Este código funciona para qualquer parcela de seaborn baseada em Grid classe
 18
Author: Serenity, 2017-07-20 10:43:11