Search code examples
pythonmatplotlibseabornfacet-grid

Increase space between rows on FacetGrid plot


I've the following code which creates the plot you can see in the picture:

g = sns.FacetGrid(data, col="Provincia",col_wrap=6,size=2.5)
g.map(sns.barplot, "Anio", "Diff");
g.set_axis_labels("Año", "Porcentaje de aumento");

for ax in g.axes.flat:
    _ = plt.setp(ax.get_yticklabels(), visible=True)
    _ = plt.setp(ax.get_xticklabels(), visible=False)
    _ = plt.setp(ax.get_xticklabels()[0], visible=True)    
    _ = plt.setp(ax.get_xticklabels()[-1], visible=True)

The problem, as you can see in the picture, is that the x ticks collapse with the col name below. What is the proper way to increase this space in order to fix this?

output


Solution

  • tight layout

    You can use tight_layout to automatically adjust the spacings

    g.fig.tight_layout()
    

    or, if you have matplotlib.pyplot imported as plt,

    plt.tight_layout()
    

    subplots adjust

    You can use plt.subplots_adjust to manually set the spacings between subplots,

    plt.subplots_adjust(hspace=0.4, wspace=0.4)
    

    where hspace is the space in height, and wspace is the space width direction.

    gridspec keyword arguments

    You could also use gridspec_kws in the FacetGrid initialization,

    g = sns.FacetGrid(data, ... , gridspec_kws={"wspace":0.4})
    

    However, this can only be used if col_wrap is not set. (So it might not be an option in the particular case from the question).