访问seaborn lmplot中的轴对象

naz*_*azz 5 python data-visualization matplotlib seaborn

大多数 seaborn 绘图函数(例如seaborn.barplot, seaborn.regplotmatplotlib.pyplot.axes在调用时返回 a ,以便您可以使用此对象进一步自定义绘图,因为您认为合适。

但是,我想创建一个seaborn.lmplot不返回轴对象的 。在深入研究seaborn.lmplotseaborn.FacetGridlmplot在后端使用)的文档后,我发现无法访问底层axes对象。此外,虽然大多数其他 seaborn 函数允许您将自己的函数axes作为参数传递,它们将在其上绘制绘图,lmplot 但不是.

我想到的一件事是使用plt.gca(),但这只会返回网格的最后一个 axes对象。

有没有办法访问或 中的axes对象?seaborn.lmplotseaborn.FacetGrid

Dji*_*011 5

是的,您可以matplotlib.pyplot.axes像这样访问对象:

import seaborn as sns
lm = sns.lmplot(...)  # draw a grid of plots
ax = lm.axes  # access a grid of 'axes' objects
Run Code Online (Sandbox Code Playgroud)

这里,ax是一个包含子图中所有轴对象的数组。您可以像这样访问每一个:

ax.shape  # see the shape of the array containing the 'axes' objects
ax[0, 0]  # the top-left (first) subplot 
ax[i, j]  # the subplot on the i-th row of the j-th column
Run Code Online (Sandbox Code Playgroud)

如果只有一个子图,您可以按照我上面显示的方式访问它(使用ax[0, 0]),或者如您在问题中通过 ( plt.gca())所说的那样访问它