一尘不染

编辑seaborn legend

python

使用数据帧和Python中的代码,我可以创建一个绘图:

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 [%]')

但是传说中说“+0”和“。1“对读者没什么帮助。如何编辑图例的标签?最好不要说“千禧年”吧会说“一代”和“+Millennial”。老一辈人”


阅读 362

收藏
2020-12-20

共1个答案

一尘不染

如果“legend_out”设置为“True”,则可以使用“g.\u legend”`
属性,它是图形的一部分。Seaborn legend是标准的matplotlib
图例对象。因此,您可以更改图例文本,例如:

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()

另一种情况是如果将“legend”设置为“False”。你必须定义
轴有一个图例(在下面的示例中,轴编号为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()

此外,您可以结合两种情况使用以下代码:

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()

This code works for any seaborn plot which is based on Grid
class
.

2020-12-20