[英]How to move the legend in Seaborn FacetGrid outside of the plot
您可以通過調整繪圖大小來做到這一點:
g = sns.FacetGrid(df, row="Type", hue="Name", size=3, aspect=3)
g = g.map(sns.plt.plot, "Volume", "Index")
for ax in g.axes.flat:
box = ax.get_position()
ax.set_position([box.x0,box.y0,box.width*0.9,box.height])
sns.plt.legend(loc='center left',bbox_to_anchor=(1,0.5))
sns.plt.show()
示例:
import seaborn as sns
tips = sns.load_dataset('tips')
# more informative values
condition = tips['smoker'] == 'Yes'
tips['smoking_status'] = ''
tips.loc[condition,'smoking_status'] = 'Smoker'
tips.loc[~condition,'smoking_status'] = 'Non-Smoker'
g = sns.FacetGrid(tips,row='sex',hue='smoking_status',size=3,aspect=3)
g = g.map(plt.scatter,'total_bill','tip')
for ax in g.axes.flat:
box = ax.get_position()
ax.set_position([box.x0,box.y0,box.width*0.85,box.height])
sns.plt.legend(loc='upper left',bbox_to_anchor=(1,0.5))
sns.plt.show()
結果:
按照 Seaborn 文檔,您可以將 arg legend_out=True
添加到您的電話中,這應該可以解決問題
https://seaborn.pydata.org/generated/seaborn.FacetGrid.html
你的代碼看起來像
g = sns.FacetGrid(df, row="Type", hue="Name", size=3, aspect=3, legend_out=True)
g = (g.map(plt.plot, "Volume", "Index").add_legend())
plt.show()
根據上面 mwaskom 的評論,這是 OS X 中的一個錯誤。確實切換到另一個后端解決了這個問題。
例如,我把它放到我的matplotlibrc
:
backend : TkAgg # use Tk with antigrain (agg) rendering
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.