我见过Creating multi column legend in python seaborn plot但我认为我的问题有点不同。简而言之,我有一个正在绘制的数据框 seaborn
的lmplot
并得到 FacetGrid
。问题是,hue
有大量的值。所以我得到了一个超长的单列图例。代码示例如下:
ers = sns.lmplot(
data=emorb,
x="Pb",
y="Nd",
row="Ridge Sys",
hue="Seg Name",
scatter=True,
fit_reg=False,
scatter_kws={"alpha":0.7, "edgecolor": "w"},
palette=sns.color_palette("bright", 20),
legend=True
)
ers.set(ylim=(0.5122,0.5134))
我可以访问通过调用 ers._legend
创建的图例对象这将返回一个类型为 Legend
的对象(基本上,一个 matplotlib
对象)。但是,我无法调用此图例对象来更改列数,例如:
l = ers._legend
l(ncols=9)
有什么建议,或者我是否遗漏了一些可能更明显的东西,例如重新绘制图例并指定任何参数的方法?
谢谢。
最佳答案
哎呀,明白了:
FacetGrid
对象有一个属性 fig
,即
g = sns.lmplot()
parent_mpl_figure = g.fig
因此,如果我在 sns.lmplot()
中设置 legend=False
,我就可以指定 parent_mpl_figure.legend(labels=[], ncol= 9、bbox_to_anchor=(1,1))
。
写得干净:
g = sns.lmplot(legend = False)
parent_mpl_figure = g.fig
parent_mpl_figure.legend(labels = [], ncol = 9, bbox_to_anchor = (1,1))
希望这对其他人/现在了解如何让每个 Facet
跨越整个调色板以便每个 Facet 中的不同
组更容易区分...hue
组有所启发
关于python - seaborn/matplotlib 更改图例对象中的列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398469/