python – 编辑seaborn传奇

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

python  – 编辑seaborn传奇

但是,传说中的“0”和“.1”对读者来说并不是很有帮助.如何编辑图例的标签?理想情况下,它不是说“千禧年”,而是说“一代”和“千禧一代”.“老一代”

解决方法:

如果legend_out设置为True,则认为g._legend属性可以使用图例,它是图形的一部分. Seaborn图例是标准的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()

python  – 编辑seaborn传奇

如果legend_out设置为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()

python  – 编辑seaborn传奇

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

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 class的seaborn图.

上一篇:python – pandas和seaborn – 没有颜色的热图


下一篇:C#编程(六十一)------------LINQ中的扩展方法