seaborn 图例(函数与对象)

问题描述 投票:0回答:1

使用seaborn函数时,我可以获得所有句柄和标签:

p=(
sns.scatterplot(data=peng, x='island', y='bill_length_mm', hue='species', style='sex')
)
print(type(p))
h, l = p.get_legend_handles_labels()
print(l)

['物种', 'Adelie', 'Chinstrap', 'Gentoo', '性别', '男性', '女性']

但是当使用seaborn对象时我得到空列表:

p=(
so.Plot(data=peng, x='island', y='bill_length_mm', color='species',
        pointsize='species', fill='sex', marker='sex')
    .layout(size=(6,5))
    .add(so.Dots(stroke=0.5), so.Jitter(0.4))
    .scale(marker=["o", (6, 2, 1)], pointsize=(6,8), color='flare')
    .plot()
)

ax, = p._figure.axes
h, l = ax.get_legend_handles_labels()
print(l)

[]

有什么方法可以帮助解决这个问题吗?

python matplotlib seaborn seaborn-objects
1个回答
-1
投票

seaborn 对象 API 将图例而不是斧头添加到图形中。您可以循环

p._legend_contents
来获取手柄标签:

p=(
so.Plot(data=peng, x='island', y='bill_length_mm', color='species',
        pointsize='species', fill='sex', marker='sex')
    .layout(size=(6,5))
    .add(so.Dots(stroke=0.5), so.Jitter(0.4))
    .scale(marker=["o", (6, 2, 1)], pointsize=(6,8), color='flare')
    .plot()
)

for key, artists, labels in p._legend_contents:
    print(f'{key[0]}: {labels}')

输出:

species: ['Adelie', 'Gentoo', 'Chinstrap']
sex: ['male', 'female']
© www.soinside.com 2019 - 2024. All rights reserved.