python - 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:
Instead I would like to have a single legend looking something like this:
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
解决方案
由于您似乎想将图例放在图上方,我会指示 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
推荐阅读
- java - 在控制器中映射 URL(从相关表中删除数据) Spring Boot
- javascript - Bootstrap 将样式应用于表单中不需要的输入。
- delphi - TidHTTP Request 在 Fiddler 运行时有效,但在关闭时无效
- grpc - gPRC如何将数组数据从服务器发送到客户端[gPRC + Node.js]
- d3.js - 如果要缩放,要计算缩放和平移的转换值
- css - mat-form-field 样式如何自动填充标签?
- python - 使用具有不同数据框形状的 matplotlib 绘制条形图
- powershell - 从 CMD 使用时如何正确引用 PowerShell 命令路径
- c++ - `BOOST_ENDIAN_BIG_BYTE` 和 `BOOST_ENDIAN_BIG_WORD` 有什么区别?
- amazon-web-services - 让 SSL 在 AWS on Ghost 中工作 by bitnami