Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何控制Seaborn-Python中的图例_Python_Matplotlib_Legend_Seaborn - Fatal编程技术网

如何控制Seaborn-Python中的图例

如何控制Seaborn-Python中的图例,python,matplotlib,legend,seaborn,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 im

我试图找到如何控制和定制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')

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


您的建议将不胜感激。

我一直发现,一旦seaborn地块被创建,更改其标签会有点棘手。最简单的解决方案似乎是通过映射值和列名来更改输入数据本身。可以按如下所示创建新的数据框,然后使用相同的绘图命令

data = surveys_by_year_sex_long.rename(columns={'sex': 'Sex'})
data['Sex'] = data['Sex'].map({'M': 'Male', 'F': 'Female'})
sn.factorplot(
    x = "year", y = "wgt", data = data, hue = "Sex",
    kind = "bar", legend_out = True,
    palette = sn.color_palette(palette = ["SteelBlue" , "Salmon"]),
    hue_order = ["Male", "Female"])


希望这能满足你的需要。潜在的问题是,如果数据集很大,以这种方式创建一个全新的数据帧会增加一些开销。

首先,需要通过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)
结果并不完全令人满意,因为图例中的字符串比以前大,因此图例将与绘图重叠

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

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

作为补充说明,此解决方案仅适用于使用图形级界面的绘图功能。例如,对于其他函数,
sns.boxplot()
解决方法是直接声明并调用
matplotlib
axis对象。切中要害。作品请接受+1作为满足点,好先生!