Search code examples
pythonplotseabornscalingfacet-grid

Scaling facets to fit the data and use maximum available space using FacetGrid in seaborn


I am working with the FacetGrid example presented here where FacetGrid object is initialised with the code snippet below, resulting in the plot following.

# Initialize the FacetGrid object
g = sns.FacetGrid(df, row="g", hue="g", height=2, aspect=10, palette=sns.color_palette("Blues", 1))

# Draw the densities in a few steps
g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)
g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2)
g.map(plt.axhline, y=0, lw=2, clip_on=False)

enter image description here

I have added value labels to all facets and I would like to modify it further to scale each of the facets, as I have a lot of cases where the values go beyond the maximum space of the facet, and some cases where it is not possible to see the data, due to the values not being dense enough. The first group of cases is presented below, and you can see how the labels go beyond to the next facet, reducing the clarity of the plot.

enter image description here

What I would like to achieve is a separate scaling of each facet, with the values marked, and the maximum value placed on the top of the available facet space.


Solution

  • I solved it, once commenting out the line below, the facets are not overlapping anymore:

    # Set the subplots to overlap
    g.fig.subplots_adjust(hspace=-.25)
    

    Furthermore, following the suggestions in the comments, I set the value to a positive number to bring the facets closer to each other, but without introducing the overlaps between the labels of the neighbouring facets. I found the value of 0.2 to suit the needs well:

    g.fig.subplots_adjust(hspace=.2)
    

    Then sharey=False argument in FacetGrid constructor is working. It looks much cleaner, but the values are not all the way to fill the whole available space, but that is maybe intended.

    g = sns.FacetGrid(df, row="g", hue="g", height=2, aspect=10, sharey=False, palette=sns.color_palette("Blues", 1))
    

    enter image description here