编辑海上传奇 [英] Edit seaborn legend

查看:61
本文介绍了编辑海上传奇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using a data frame and this code in Python, I was able to create a plot:

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"对读者不是很有帮助.如何编辑图例的标签?理想情况下,与其说千禧一代",不如说一代"和"+千禧一代".老一辈"

However having the legend say "+ 0" and ". 1" isn't very helpful to readers. How can I edit the legend's labels? Ideally instead of saying 'millennial' it would say 'Generation' and "+ Millennial" ". Older Generations"

推荐答案

如果legend_out设置为True,则可以通过g._legend属性使用图例,并且它是图形的一部分. Seaborn图例是标准的matplotlib图例对象.因此,您可以更改图例文本,例如:

If legend_out is set to True then legend is available thought g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:

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_out设置为False的另一种情况.您必须定义哪些轴具有图例(在下面的示例中,这是轴号0):

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

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

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

Moreover you may combine both situations and use this code:

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

此代码适用于任何基于 Grid.

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

这篇关于编辑海上传奇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆