How to add suptitle to a facet plot created using the seaborn.objects api?

72 Views Asked by At

I tried to find a way to add a separate suptitle to a set of subplots created using the seaborn.objects API. However, I couldn't find any such examples in the the docs. Is there a way to do this?

I have tried adding a suptitle using label and although it does not throw an error it does not do anything.

p = (
  so.Plot(data, x="time", y="value", color='cols')
  .add(so.Area(alpha=0.9), so.Stack())
  .scale(color=colors)
)

(
  p.label(suptitle=f'Good')
  .label(x='Time (min)', y='Fraction', color='')
  .limit(y=(0, 1), x=(0, 247.5))
  .facet("posnum", wrap=3)
  .share(y=True, x=True)
  .layout(size=(10,10))
  .label(suptitle=f'Good')
)
2

There are 2 best solutions below

0
Rocco Fortuna On

In the seaborn.objects API, adding a title or suptitle to a facet plot isn't directly supported as a method or attribute within the objects API itself. Instead, you can utilize the underlying matplotlib functions to achieve this, as the seaborn plots are built on top of matplotlib.

After you have created your facet plot using the seaborn.objects API, you can add a suptitle by accessing the matplotlib figure object that seaborn is using under the hood. Here is how you can modify your code to include a suptitle:

import seaborn.objects as so
import matplotlib.pyplot as plt

# Your code for the plot
p = (so.Plot(data, x="time", y="value", color='cols')
     .add(so.Area(alpha=0.9), so.Stack())
     .scale(color=colors)
     .limit(y=(0, 1), x=(0, 247.5))
     .facet("posnum", wrap=3)
     .share(y=True, x=True)
     .layout(size=(10, 10)))

# Draw the plot
ax_dict = p.draw()

# Access the figure from any of the axes and set suptitle
fig = list(ax_dict.values())[0].figure  # Get the figure object
fig.suptitle('Good', fontsize=16)  # Set the suptitle

plt.show()
0
Hericks On

As answered in a similar question here. This is currently only possible by going through the matplotlib interface.

Specifically, you can use so.Plot.on as follows.

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()
)