如何将seaborn图例分成多列?

2024-09-30 10:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用不同色调和样式的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

解决此问题的最小工作示例:

^{pr2}$

minimal working example output



Tags: the示例plot条目样式色调height图例
2条回答

最终解决方案感谢@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

因为您似乎希望将图例放在图的上方,我将指示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

相关问题 更多 >

    热门问题