首页 > 解决方案 > How to split seaborn legend into multiple columns?

问题描述

I use a relplot with different hue and style and would like to show the respective legend entries besides instead of below each other.

So currently I get a legend like this:

relplot legend with hue and style labels below each other

Instead I would like to have a single legend looking something like this:

relplot legend with hue and style labels besides each other

How can this be done?

I tried setting the following but that had no effect:

plot._legend
leg._ncol = 2
leg.handleheight = 1  # restricting the height

Minimal working example to solve this problem:

import pandas as pd
import seaborn as sns

columns = ['category1', 'category2', 'category3', 'time', 'value']

data = [['content1', 'other1', 'critera1', 0, 0.1], ['content1', 'other1', 'critera1', 1, 0.4], ['content1', 'other1', 'critera1', 2, 0.7], ['content2', 'other1', 'critera1', 0, 0.2], ['content2', 'other1', 'critera1', 1, 0.6], ['content2', 'other1', 'critera1', 2, 0.8], ['content1', 'other2', 'critera1', 0, 0.0], ['content1', 'other2', 'critera1', 1, 0.2], ['content1', 'other2', 'critera1', 2, 0.8], ['content2', 'other2', 'critera1', 0, 0.3], ['content2', 'other2', 'critera1', 1, 0.6], ['content2', 'other2', 'critera1', 2, 0.5], [
    'content1', 'other1', 'critera2', 0, 0.1], ['content1', 'other1', 'critera2', 1, 0.4], ['content1', 'other1', 'critera2', 2, 0.7], ['content2', 'other1', 'critera2', 0, 0.2], ['content2', 'other1', 'critera2', 1, 0.6], ['content2', 'other1', 'critera2', 2, 0.8], ['content1', 'other2', 'critera2', 0, 0.0], ['content1', 'other2', 'critera2', 1, 0.2], ['content1', 'other2', 'critera2', 2, 0.8], ['content2', 'other2', 'critera2', 0, 0.3], ['content2', 'other2', 'critera2', 1, 0.6], ['content2', 'other2', 'critera2', 2, 0.5], ]

df = pd.DataFrame(data, columns=columns)

plot = sns.relplot(x='time', y='value', col='category3', hue='category1', style='category2', kind="line", col_wrap=2, data=df)

leg = plot._legend
leg.set_bbox_to_anchor((0.5, 1.3, 0, 0))
leg._loc = 9

minimal working example output


标签: pythonmatplotlibseabornlegend

解决方案


由于您似乎想将图例放在图上方,我会指示 seaborn 不要使用legend_out=False. 然后只需获取 seaborn 创建的句柄和标签,并使用ncol=2. 请注意,只有当两列中的元素数量相同时,这才会有效,否则事情会变得一团糟。

plot = sns.relplot(x='time', y='value', col='category3', hue='category1', style='category2', kind="line", col_wrap=2, data=df, facet_kws=dict(legend_out=False))
h,l = plot.axes[0].get_legend_handles_labels()
plot.axes[0].legend_.remove()
plot.fig.legend(h,l, ncol=2) # you can specify any location parameter you want here

推荐阅读