-1

假设我有一个名为 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 对象。

4

1 回答 1

1

如果您查看帮助页面,它会写道:

用于在 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

在此处输入图像描述

于 2020-10-08T16:58:10.220 回答