Search code examples
pythonseabornseaborn-objects

How to add a general title with a seaborn.objects.Plot.facet plot


I am currently using the seaborn library in Python to create a facetted stacked barplot from a pandas dataframe named averages with columns ['Name', 'Period', 'Value', 'Solver'].

Here is the code I use to create the plot I want.

p = so.Plot(data = averages, x = 'Period', y = 'Value', color = 'Name').add(so.Bar(), so.Stack(), suptitle='Inventory levels')
p = p.facet(col='Solver', order=['spse', 'mp2', 'mels'])

I am searching for a way to add a general title to the plot i.e. a title above each subplot, like the function matplotlib.pyplot.suptitle function does for example.

I know that the function seaborn.objects.Plot.label has a title= option, but when I use it, this puts the same title above each subplot of the facetted graph.


Solution

  • You can provide an existing Matplotlib figure or axes for drawing the plot using so.Plot.on. This gives you access to the underlying matplotlib.figure.Figure object to which the suptitle can be added.

    import matplotlib.pyplot as plt
    import seaborn.objects as so
    import pandas as pd
    
    df = pd.DataFrame({
        "x": [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
        "y": [1, 2, 3, 4, 5, 1, 2, 4, 8, 16],
        "group": ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"],
    })
    
    fig = plt.Figure()
    fig.suptitle("Suptitle")
    
    (
        so.Plot(df, x="x", y="y")
        .add(so.Line())
        .facet(col="group")
        .on(fig)
        .plot()
    )