在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"对读者来说并不是很有帮助。如何编辑图例的标签?理想情况下,而不是说千禧年'它会说'一代''和" +千禧年" &#34 ;.老一代"
答案 0 :(得分:30)
如果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()
如果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()
此外,您可以结合使用这两种情况并使用此代码:
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图。
答案 1 :(得分:0)
如果只想更改图例标题,则可以执行以下操作:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=True
)
g._legend.set_title("New Title")