catplot issue Axes object

307 views Asked by At

Supposing I have a Pandas DataFrame variable called df which has columns col1, col2, col3, col4.

Using sns.catplot() everything works fine:

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

However, as soon as I write:

fig.axes[0].get_xlabel()

I get the following error:

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

I know I can use sns.barplot() with ax parameter but my goal is to keep using sns.catplot() and get an Axes object from fig.axes[0].

1

There are 1 answers

2
StupidWolf On BEST ANSWER

If you check the help page, it writes:

Figure-level interface for drawing categorical plots onto a FacetGrid

So to get the xlabel like you did:

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

enter image description here

In this example, you have a facet plot that is 1 by 2, so the axes for the plots are stored in an (1,2) array:

g.axes.shape
(1, 2)

And to access for example the one of the left (Smoker ="Yes"), you do:

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

To change the label:

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

enter image description here