如何在Seaborn中控制图例-Python [英] How to control the legend in Seaborn - Python
问题描述
我正在尝试找到有关如何控制和自定义Seaborn地块中图例的指南,但找不到任何内容.
I am trying to find guidance on how to control and customize the legend in Seaborn plots but I can not find any.
为了使问题更具体,我提供了一个可重现的示例:
To make the issue more concrete I provide a reproducible example:
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')
在这个示例中,我希望能够将M定义为Male,将F定义为Female,而不是将sex定义为图例的标题.
In this example I would like to be able to define M as Male and F as Female and instead of sex to have Sex as title of the legend.
您的建议将不胜感激.
推荐答案
首先,需要通过seaborn调用来访问seaborn创建的图例.
First, to access the legend created by seaborn needs to be done via the seaborn call.
g = sns.factorplot(...)
legend = g._legend
然后可以操纵此图例,
legend.set_title("Sex")
for t, l in zip(legend.texts,("Male", "Female")):
t.set_text(l)
结果并不完全令人满意,因为图例中的字符串比以前大,因此图例将与情节重叠
The result is not totally pleasing because the strings in the legend are larger than previously, hence the legend would overlap the plot
因此,还需要稍微调整图形边距,
One would hence also need to adjust the figure margins a bit,
g.fig.subplots_adjust(top=0.9,right=0.7)
这篇关于如何在Seaborn中控制图例-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!