Я использую повторный график с другим оттенком и стилем и хотел бы показывать соответствующие записи легенды, а не друг под другом.
Итак, в настоящее время я получаю такую легенду:
Вместо этого я хотел бы, чтобы одна легенда выглядела примерно так:
Как это может быть сделано?
Я попытался установить следующее, но это не дало никакого эффекта:
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
Возможный дубликат Разделите морскую легенду на две отдельные коробки.
@DizietAsahi Спасибо за ссылку, но они все равно должны быть в одной легенде.
@ImportanceOfBeingErnest Я добавил MWE.
Поскольку вы, кажется, хотите разместить легенду над графиками, я бы посоветовал 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
Спасибо, это помогло получить то, что я хотел. Я добавил свое окончательное решение к моему вопросу.
Окончательное решение благодаря @DizieAsahi
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)
Используйте ncol
ax = sns.barplot(x = "X", y = "Y", data=data)
ax.legend(loc='upper left',ncol=2, title = "Title")
Нет встроенного способа сделать это. И даже если бы можно было менять количество столбцов на лету, это выглядело бы не так, как вы ожидаете. Так что вам нужно будет воссоздать легенду с нуля. Если вам нужен ответ о том, как это сделать, было бы неплохо предоставить потенциальным ответчикам минимальный воспроизводимый пример, которые они могут использовать для демонстрации решения.