Constantino
Constantino

Reputation: 2391

set axis limits on individual facets of seaborn facetgrid

I'm trying to set the x-axis limits to different values for each facet a Seaborn facetgrid distplot. I understand that I can get access to all the axes within the subplots through g.axes, so I've tried to iterate over them and set the xlim with:

g = sns.FacetGrid(
    mapping,
    col=options.facetCol,
    row=options.facetRow,
    col_order=sorted(cols),
    hue=options.group,
)
g = g.map(sns.distplot, options.axis)

for i, ax in enumerate(g.axes.flat):  # set every-other axis for testing purposes
    if i % 2 == 0[enter link description here][1]:
        ax.set_xlim(-400, 500)
    else:
        ax.set_xlim(-200, 200)

However, when I do this, all axes get set to (-200, 200) not just every other facet.

What am I doing wrong?

Upvotes: 28

Views: 20209

Answers (2)

Constantino
Constantino

Reputation: 2391

mwaskom had the solution; posting here for completeness - just had to change the following line to:

g = sns.FacetGrid(
    mapping,
    col=options.facetCol,
    row=options.facetRow,
    col_order=sorted(cols),
    hue=options.group,
    sharex=False,  # <- This option solved the problem!
)

Upvotes: 37

cglacet
cglacet

Reputation: 10912

As suggested by mwaskom you can simply use FacetGrid's sharex (respectively sharey) to allow plots to have independent axis scales:

share{x,y} : bool, ‘col’, or ‘row’ optional

If true, the facets will share y axes across columns and/or x axes across rows.

For example, with:

  • sharex=False each plot has its own axis
  • sharex='col' each column has its own axis
  • sharex='row' each row has its own axis (even if this one doesn't make too much sense to me)
sns.FacetGrid(data, ..., sharex='col')

If you use FacetGrid indirectly, for example via displot or relplot, you will have to use the facet_kws keyword argument:

sns.displot(data, ..., facet_kws={'sharex': 'col'})

Upvotes: 6

Related Questions