catplot 问题 Axes 对象

catplot issue Axes object

假设我有一个名为 df 的 Pandas DataFrame 变量,其中包含列 col1、col2、col3、col4。

使用 sns.catplot() 一切正常:

fig = sns.catplot(x='col1', y='col2', kind='bar', data=df, col='col3', hue='col4') 

然而,我一写:

fig.axes[0].get_xlabel()

我收到以下错误:

AttributeError: 'numpy.ndarray' object has no attribute 'get_xlabel'

我知道我可以将 sns.barplot() 与 ax 参数一起使用,但我的目标是继续使用 sns.catplot() 并从 fig.axes[0] 获取 Axes 对象。

如果您检查 help page,它会显示:

Figure-level interface for drawing categorical plots onto a FacetGrid

所以要像您一样获得 xlabel:

import seaborn as sns
df = sns.load_dataset("tips")
g = sns.catplot(x='day', y='tip', kind='bar', data=df, col='smoker', hue='sex') 

在此示例中,您有一个 1 x 2 的分面图,因此图的轴存储在 (1,2) 数组中:

g.axes.shape
(1, 2)

要访问例如左边的那个(Smoker ="Yes"),您需要:

g.axes[0,0].get_xlabel()
'day'

要更改标签:

g.axes[0,0].set_xlabel('day 1')
g.fig