Spe*_*pen 6 python matplotlib legend seaborn
我使用具有不同色调和样式的 relplot,并希望显示各自的图例条目,而不是彼此下方。
所以目前我得到一个这样的传说:
相反,我希望有一个看起来像这样的图例:
如何才能做到这一点?
我尝试设置以下但没有效果:
plot._legend
leg._ncol = 2
leg.handleheight = 1 # restricting the height
Run Code Online (Sandbox Code Playgroud)
解决此问题的最小工作示例:
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
Run Code Online (Sandbox Code Playgroud)
由于您似乎想将图例放在图上方,我会指示 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
Run Code Online (Sandbox Code Playgroud)
使用ncol
ax = sns.barplot(x="X", y="Y", data=data)
ax.legend(loc='upper left',ncol=2, title="Title")
Run Code Online (Sandbox Code Playgroud)