python - 如何在 Seaborn 中控制图例 - Python

标签 python matplotlib legend seaborn

这个问题在这里已经有了答案:





How to edit a seaborn legend title and labels for figure-level functions

(2 个回答)


3个月前关闭。




我试图找到有关如何控制和自定义 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 定义为女性,而不是将性别作为图例的标题。

您的建议将不胜感激。

最佳答案

首先,需要通过 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

关于python - 如何在 Seaborn 中控制图例 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47542104/

相关文章:

python - Python 中数组的 2D 和 3D 散点直方图

r - 为ggplot2中的每个图例分配不同的背景颜色

python - 在 matplotlib 中为图例中的标签部分设置样式

r - 是否可以在scale_fill_gradient2()中定义 "mid"范围?

python - 如何从 Tkinter Text Widget 获取输入?

python - 验证 sqlalchemy session

python-3.x - Matplotlib:每个刻度都有不同的颜色

python - 将应用程序添加到 Django

python - 在其他语言中使用 PBKDF2 SHA512 数据

python - 如何在 python 中绘制我的目的图?