23

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?

AllanLRH
  • 1,124
  • 1
  • 12
  • 23
Constantino
  • 2,243
  • 2
  • 24
  • 41

2 Answers2

33

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!
)
AllanLRH
  • 1,124
  • 1
  • 12
  • 23
Constantino
  • 2,243
  • 2
  • 24
  • 41
3

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'})
cglacet
  • 8,873
  • 4
  • 45
  • 60