如何将 Seaborn FacetGrid 中的图例移出情节
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")
g.add_legend()
sns.plt.show()
结果如下图:
如何将图例移出情节?
您可以通过调整图的大小来做到这一点:
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()
结果:
根据上面 mwaskom 的评论,这是 OS X 中的一个错误。确实切换到另一个后端解决了这个问题。
例如,我将其放入 matplotlibrc
:
backend : TkAgg # use Tk with antigrain (agg) rendering
按照 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()
我有以下代码:
g = sns.FacetGrid(df, row="Type", hue="Name", size=3, aspect=3)
g = g.map(sns.plt.plot, "Volume", "Index")
g.add_legend()
sns.plt.show()
结果如下图:
如何将图例移出情节?
您可以通过调整图的大小来做到这一点:
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()
结果:
根据上面 mwaskom 的评论,这是 OS X 中的一个错误。确实切换到另一个后端解决了这个问题。
例如,我将其放入 matplotlibrc
:
backend : TkAgg # use Tk with antigrain (agg) rendering
按照 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()