Search code examples
pythonseabornfacet-grid

How to reposition title in seaborn.FacetGrid if tight_layout is applied?


I have a simple seaborn FacetGrid() with barplots inside.

I applied tight_layout() to my final plot, as xticks had to be properly positioned on the plot after rotation. As result, when I want to add the title to the plot it is positioned in the wrong place, basically over the existing axes.

So, my question is how should the title be manipulated in order to be properly positioned in case tight_layout() is applied?

I reproduced the issue with the standard tips dataset:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")

days_dict = {day:day+', a long name' for day in tips['day'].unique()}
tips['day_long'] = tips['day'].map(lambda x: days_dict[x])

grid = sns.FacetGrid(tips,col='size',col_wrap=3,height=4,sharex=False)

grid.map(sns.barplot, 'day_long', 'total_bill').set_titles('{col_name}')
grid.fig.set_size_inches(10,10)
grid.fig.suptitle('Title (it should be placed higher)',fontsize=16)

for ax in grid.axes.flat:
    for label in ax.get_xticklabels():
        label.set_rotation(90)

plt.tight_layout()
plt.show()

enter image description here


Solution

  • Add (adjust the value to your taste)

    grid.fig.subplots_adjust(top=0.90)
    

    after tight_laout() to make some room at the top of the plot for the suptitle()