rf7*_*rf7 3 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')
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我希望能够将 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"])
Run Code Online (Sandbox Code Playgroud)
希望这能满足您的需要。潜在的问题是,如果数据集很大,以这种方式创建一个全新的数据框会增加一些开销。
首先,需要通过 seaborn 调用访问由 seaborn 创建的图例。
g = sns.factorplot(...)
legend = g._legend
Run Code Online (Sandbox Code Playgroud)
然后可以操纵这个传说,
legend.set_title("Sex")
for t, l in zip(legend.texts,("Male", "Female")):
t.set_text(l)
Run Code Online (Sandbox Code Playgroud)
结果并不完全令人满意,因为图例中的字符串比以前大,因此图例会与情节重叠
因此,还需要稍微调整图形边距,
g.fig.subplots_adjust(top=0.9,right=0.7)
Run Code Online (Sandbox Code Playgroud)