如何控制Seaborn-Python中的传奇

2024-09-29 01:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到指导,如何控制和定制在海生情节的传奇,但我找不到任何。

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

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为女性,而不是性,以性作为传说的标题。

你的建议将不胜感激。


Tags: fromimportbymatplotlibaspltyearhue
2条回答

我总是发现,一旦海生地块被创造出来,改变它们的标签就有点棘手。最简单的解决方案似乎是通过映射值和列名来更改输入数据本身。您可以按如下方式创建新的数据帧,然后使用相同的打印命令。

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"])

Updated names

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

首先,要访问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

相关问题 更多 >