Как разбить легенду о морском раке на несколько столбцов - PullRequest
1 голос
/ 13 июня 2019

Я использую relplot с другим оттенком и стилем и хотел бы показывать соответствующие записи легенды, а не под ними.

Так что в настоящее время я получаю легенду, подобную этой:

relplot legend with hue and style labels below each other

Вместо этого я хотел бы, чтобы одна легенда выглядела примерно так:

relplot legend with hue and style labels besides each other

Как это можно сделать?

Я попытался установить следующее, но это не дало эффекта:

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

Минимальный рабочий пример для решения этой проблемы:

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


Ответы [ 2 ]

2 голосов
/ 13 июня 2019

Поскольку вы, кажется, хотите разместить легенду над графиками, я бы поручила морскому роду не резервировать место справа для легенды, используя 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
0 голосов
/ 13 июня 2019

Окончательное решение благодаря @ DizietAsahi

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)

handles, labels = plot.axes[0].get_legend_handles_labels()
plot._legend.remove()
plot.fig.legend(handles, labels, ncol=2, loc='upper center', 
                bbox_to_anchor=(0.5, 1.15), frameon=False)

solution

...