2024-09-30 10:35:38 发布
网友
我使用不同色调和样式的relplot,并希望显示各自的图例条目,而不是在彼此下面。在
所以现在我得到了这样一个传说:
相反,我希望有一个像这样的传说:
如何做到这一点?
我试着设置以下内容,但没有效果:
plot._legend leg._ncol = 2 leg.handleheight = 1 # restricting the height
解决此问题的最小工作示例:
最终解决方案感谢@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)
因为您似乎希望将图例放在图的上方,我将指示seaborn不要使用legend_out=False在右侧为图例保留空间。然后,只需获取seaborn创建的句柄和标签,并使用ncol=2生成一个新的图例。请注意,只有当两列中的元素数量相同时,这才有效,否则事情会变得一团糟。在
legend_out=False
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
最终解决方案感谢@DizietAsahi
因为您似乎希望将图例放在图的上方,我将指示seaborn不要使用
legend_out=False
在右侧为图例保留空间。然后,只需获取seaborn创建的句柄和标签,并使用ncol=2
生成一个新的图例。请注意,只有当两列中的元素数量相同时,这才有效,否则事情会变得一团糟。在相关问题 更多 >
编程相关推荐