簡體   English   中英

如何將傳說放在seaborn.FacetGrid的第一個子圖上?

[英]How to put the legend on first subplot of seaborn.FacetGrid?

我有一個pandas DataFrame df ,我用seaborn.barplot子圖可視化。 我的問題是我想把我的傳說移到其中一個子圖中。

要根據條件(在我的案例中為Area )創建子圖,我使用seaborn.FacetGrid 這是我使用的代碼:

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()

這產生了這個情節:

barplot,所有

你看到這里的圖例完全在右邊,但是我想把它放在一個圖中(例如左圖),因為我的原始數據標簽很長而且圖例占用的空間太大。 這是僅有1個繪圖的示例,其中圖例位於繪圖內:

barplot1

和代碼:

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

測試1 :我嘗試了一個答案的例子,他們在其中一個子圖中有傳說:

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()

請注意,我更改了plt.legend(handles=legend_patches)對我不起作用,因此我在本回答中使用plt.legend(legend_patches)作為評論。 結果卻是:

第三屆傳奇測試

如您所見,圖例位於第三個子圖中,顏色和標簽都不匹配。


測試2

最后,我嘗試創建一個列包裹為2( col_wrap=2 )的子圖,其中包含右下方正方形的圖例:

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

但這也導致傳說在右邊:

barplot 2cols


問題 :如何在第一個子圖中獲取圖例? 或者我如何將圖例移動到網格中的任何位置?

您可以使用grid.axes[i][j].legend()在所需的特定軸上設置圖例。

對於1 row, 3 column網格的情況,您需要將grid.axes[0][0].legend()為在左側繪圖。

這是從您的代碼派生的簡單示例,但更改為考慮樣本數據集。

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()

在此輸入圖像描述

  1. 使用legend_out=False選項。

  2. 如果要制作多面條形圖,則應使用factorplot with kind=bar 否則,如果您沒有明確指定每個方面的順序,則您的繪圖可能最終會出錯。

     import seaborn as sns tips = sns.load_dataset("tips") sns.factorplot(x="sex", y="total_bill", hue="smoker", col="day", data=tips, kind="bar", aspect=.7, legend_out=False) 

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM