如何控制Seaborn中的传奇--Python

时间:2017-11-28 22:37:30

标签: python matplotlib legend seaborn

我正在尝试找到如何控制和自定义Seaborn图中的图例的指导,但我找不到。

为了使问题更具体,我提供了一个可重复的例子:

surveys_by_year_sex_long

    year    sex wgt
0   2001    F   36.221914
1   2001    M   36.481844
2   2002    F   34.016799
3   2002    M   37.589905

%matplotlib inline
from matplotlib import *
from matplotlib import pyplot as plt
import seaborn as sn

sn.factorplot(x = "year", y = "wgt", data = surveys_by_year_sex_long, hue = "sex", kind = "bar", legend_out = True,
             palette = sn.color_palette(palette = ["SteelBlue" , "Salmon"]), hue_order = ["M", "F"])
plt.xlabel('Year')
plt.ylabel('Weight')
plt.title('Average Weight by Year and Sex')

enter image description here

在这个例子中,我希望能够将M定义为男性,将F定义为女性而不是性别,将性别定义为传奇的标题。

您的建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

首先,要访问由seaborn创建的图例,需要通过seaborn调用来完成。

g = sns.factorplot(...)
legend = g._legend

然后可以操纵此图例,

legend.set_title("Sex")
for t, l in zip(legend.texts,("Male", "Female")):
    t.set_text(l)

结果并不完全令人愉悦,因为图例中的字符串比以前大,因此图例会与图重叠

enter image description here

因此,人们还需要稍微调整数字边距,

g.fig.subplots_adjust(top=0.9,right=0.7)

enter image description here