[英]How to use the `split` argument in a `seaborn.violinplot` in a `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()
這產生了這個情節:
你看到這里的圖例完全在右邊,但是我想把它放在一個圖中(例如左圖),因為我的原始數據標簽很長而且圖例占用的空間太大。 這是僅有1個繪圖的示例,其中圖例位於繪圖內:
和代碼:
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)
但這也導致傳說在右邊:
問題 :如何在第一個子圖中獲取圖例? 或者我如何將圖例移動到網格中的任何位置?
您可以使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.