如何将图例放在seaborn.FacetGrid的第一个子图上? [英] How to put the legend on first subplot of seaborn.FacetGrid?

查看:47
本文介绍了如何将图例放在seaborn.FacetGrid的第一个子图上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Pandas DataFrame df,我用

您会看到此处的图例完全在右侧,但由于我的原始数据标签很长且图例占用了太多空间,因此我希望将其放置在其中一个图中(例如左图).这是仅 1 个图例的示例,其中图例位于图内:

和代码:

mask = df['Area']=='F3'ax = sns.barplot(x ='Param',y ='Time',hue ='Method',data = df [mask])sns.plt.show()

<小时>

测试 1:我尝试了一个

如您所见,图例位于第三个子图中,颜色和标签都不匹配.

<小时>

测试2 :

最后,我试图创建一个带有2个列换行的子图( col_wrap = 2 ),以使图例位于右下角正方形中.

grid = sns.FacetGrid(df, col="MapPubName", col_order=['F1','F2','F3'],col_wrap=2)

但这也会导致图例位于右侧:

<小时>

问题:如何在第一个子图中获取图例?或者如何将图例移动到网格中的任何位置?

解决方案

您可以使用 grid.axes [i] [j] .legend()在所需的特定轴上设置图例>

对于 1 row, 3 column 网格的情况,您希望设置 grid.axes[0][0].legend() 在左侧.

这是从您的代码派生的一个简单示例,但已更改以考虑示例数据集.

 将matplotlib.pyplot导入为plt导入 matplotlib将 seaborn 作为 sns 导入df = sns.load_dataset("提示")grid = sns.FacetGrid(df, col="day")bp = grid.map(sns.barplot,"time",'total_bill','sex')grid.axes [0] [0] .legend()bp.set_titles("{col_name}")bp.set_ylabels(时间(s)")bp.set_xlabels("数字")sns.plt.show()

I have a pandas DataFrame df which I visualize with subplots of a seaborn.barplot. My problem is that I want to move my legend inside one of the subplots.

To create subplots based on a condition (in my case Area), I use seaborn.FacetGrid. This is the code I use:

import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
# .. load data
grid = sns.FacetGrid(df, col="Area", col_order=['F1','F2','F3'])
bp = grid.map(sns.barplot,'Param','Time','Method')
bp.add_legend()
bp.set_titles("{col_name}")
bp.set_ylabels("Time (s)")
bp.set_xlabels("Number")
sns.plt.show()

Which generates this plot:

You see that the legend here is totally at the right, but I would like to have it inside one of the plots (for example the left one) since my original data labels are quite long and the legend occupies too much space. This is the example for only 1 plot where the legend is inside the plot:

and the code:

mask = df['Area']=='F3'
ax=sns.barplot(x='Param',y='Time',hue='Method',data=df[mask])
sns.plt.show()


Test 1: I tried the example of an answer where they have the legend in one of the subplots:

grid = sns.FacetGrid(df, col="Area", col_order=['F1','F2','F3'])
bp = grid.map(sns.barplot,'Param','Time','Method')
Ax = bp.axes[0]
Boxes = [item for item in Ax.get_children()
     if isinstance(item, matplotlib.patches.Rectangle)][:-1]
legend_labels  = ['So1', 'So2', 'So3', 'So4', 'So5']
# Create the legend patches
legend_patches = [matplotlib.patches.Patch(color=C, label=L) for
              C, L in zip([item.get_facecolor() for item in Boxes],
                          legend_labels)]

# Plot the legend
plt.legend(legend_patches)    
sns.plt.show()

Note that I changed plt.legend(handles=legend_patches) did not work for me therefore I use plt.legend(legend_patches) as commented in this answer. The result however is:

As you see the legend is in the third subplot and neither the colors nor labels match.


Test 2:

Finally I tried to create a subplot with a column wrap of 2 (col_wrap=2) with the idea of having the legend in the right-bottom square:

grid = sns.FacetGrid(df, col="MapPubName", col_order=['F1','F2','F3'],col_wrap=2)

but this also results in the legend being at the right:


Question: How can I get the legend inside the first subplot? Or how can I move the legend to anywhere in the grid?

解决方案

You can set the legend on the specific axes you want, by using grid.axes[i][j].legend()

For your case of a 1 row, 3 column grid, you want to set grid.axes[0][0].legend() to plot on the left hand side.

Here's a simple example derived from your code, but changed to account for the sample dataset.

import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns

df = sns.load_dataset("tips")

grid = sns.FacetGrid(df, col="day")
bp = grid.map(sns.barplot,"time",'total_bill','sex')

grid.axes[0][0].legend()

bp.set_titles("{col_name}")
bp.set_ylabels("Time (s)")
bp.set_xlabels("Number")
sns.plt.show()

这篇关于如何将图例放在seaborn.FacetGrid的第一个子图上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆