将Seaborn传奇分成两个不同的盒子 [英] Separate seaborn legend into two distinct boxes

查看:65
本文介绍了将Seaborn传奇分成两个不同的盒子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Seaborn生成多种类型的图,但此处将基于包含的数据集仅使用一个简单的示例进行说明:

I'm using Seaborn to generate many types of graphs, but will use just a simple example here for illustration purposes based on an included dataset:

import seaborn
tips = seaborn.load_dataset("tips")
axes = seaborn.scatterplot(x="day", y="tip", size="sex", hue="time", data=tips)

在此结果中,单个图例框包含两个标题时间"和性别",每个标题都有子元素.

In this result, the single legend box contains two titles "time" and "sex", each with sub-elements.

我如何轻松地将图例分成两个方框,每个方框都有一个标题? IE.一个用于指示颜色代码的图例框(可以放置在左侧),另一个用于指示尺寸代码的图例框(可以放置在右侧).

How could I easily separate the legend into two boxes, each with a single title? I.e. one for legend box indicating color codes (that could be placed at the left), and one legend box indicating size codes (that would be placed at the right).

推荐答案

我接受了 Diziet的答案并对其进行了扩展.他提供了我需要的必要语法,但正如他指出的那样,他缺少一种计算拆分图例所需的图例行数的方法.我已经添加了它,并编写了一个完整的脚本:

I took Diziet's answer and expanded on it. He produced the necessary syntax I was needing, but as he pointed out, was missing a way to calculate how many lines of legend are required for splitting the legend. I have added this, and wrote a complete script:

# Modules #
import seaborn
from matplotlib import pyplot

# Plot #
tips = seaborn.load_dataset("tips")
axes = seaborn.scatterplot(x="day", y="tip", size="sex", hue="time", data=tips)

# Legend split and place outside #
num_of_colors   = len(tips['time'].unique()) + 1
handles, labels = axes.get_legend_handles_labels()
color_hl = handles[:num_of_colors], labels[:num_of_colors]
sizes_hl = handles[num_of_colors:], labels[num_of_colors:]

# Call legend twice #
color_leg = axes.legend(*color_hl,
                        bbox_to_anchor = (1.05, 1),
                        loc            = 'upper left',
                        borderaxespad  = 0.)
sizes_leg = axes.legend(*sizes_hl,
                        bbox_to_anchor = (1.05, 0),
                        loc            = 'lower left',
                        borderaxespad  = 0.)

# We need this because the 2nd call to legend() erases the first #
axes.add_artist(color_leg)

# Adjust #
pyplot.subplots_adjust(right=0.75)

# Display #
pyplot.ion()
pyplot.show()

这篇关于将Seaborn传奇分成两个不同的盒子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆