2

I'm trying to generate different boxplots that are describing the distribution of a variable for some product families and industry groups ("Production", "Trade", "Business", "Leisure & Wellbeing").

I'd like to know:

  1. if there is a way to show only "Production", "Trade", "Business" and "Leisure & Wellbeing" in the subplots titles instead of having each time "industry_group = Production" and so on
  2. if there is a way to raise those subplot titles a little bit from the upper border of each subplot (in the image I'm posting you can clearly see that they have no space)

Below the code I'm using and here an image to show you what I get --> Catplot Image.

import matplotlib.pyplot as plt
import seaborn as sns

sns.set_context("talk")

boxplot = sns.catplot(
    x='family', 
    y='lag',
    hue="SF_type",
    col="industry_group",
    data=df1, 
    kind="box",
    orient="v",
    height=8, 
    aspect=2,
    col_wrap=1,
    order=fam_sort,
    palette='Set3',
    notch=True,
    legend=True,
    legend_out=True,
    showfliers=False,
    showmeans=True,
    meanprops={
        "marker":"o",
        "markerfacecolor":"white", 
        "markeredgecolor":"black",
        "markersize":"10"
    }
)

boxplot.fig.suptitle("Boxplots by Product Basket, Industry Group & SF Type", y=1.14)

#repeat xticks for each plot
for ax in boxplot.axes:
    plt.setp(ax.get_xticklabels(), visible=True, rotation=75)
    plt.subplots_adjust(hspace=1.2, top = 1.1)
    
#remove axis titles
for ax in boxplot.axes.flatten():
    ax.set_ylabel('')
    ax.set_xlabel('')
    limit_upper = max(df1.groupby(['family','SF_type','industry_group'])['lag'].quantile(0.75))
    plt.setp(ax.texts, text="")
    ax.set(ylim=(-10, limit_upper ))

Catplot Image Catplot Image

ti7
  • 16,375
  • 6
  • 40
  • 68

1 Answers1

5

It can be changed with set_titles(). {} to specify the column or row that is being subplotted. See docstring for more details, and the example in the official seaborn reference to modify the subtitles.

Signature: g.set_titles(template=None, row_template=None, col_template=None, **kwargs) Docstring: Draw titles either above each facet or on the grid margins.

Parameters template : string Template for all titles with the formatting keys {col_var} and {col_name} (if using a col faceting variable) and/or {row_var} and {row_name} (if using a row faceting variable). row_template: Template for the row variable when titles are drawn on the grid margins. Must have {row_var} and {row_name} formatting keys. col_template: Template for the row variable when titles are drawn on the grid margins. Must have {col_var} and {col_name} formatting keys.

import seaborn as sns
sns.set_theme(style="ticks")

titanic = sns.load_dataset("titanic")

g = sns.catplot(x="embark_town", y="age",
                hue="sex", row="class",
                data=titanic[titanic.embark_town.notnull()],
                height=2, aspect=3, palette="Set3",
                kind="violin", dodge=True, cut=0, bw=.2)
g.set_titles(template='{row_name}')

enter image description here

default:

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • If my answer helped you, please consider accepting it as the correct answer – r-beginners May 27 '21 at 03:29
  • Is it possible also to raise the subplot titles a bit? they are really sticked to the plot...thx – Stefano Puccini May 27 '21 at 07:50
  • try this: `g.set_titles(template='{row_name}',y=0.85)` – r-beginners May 27 '21 at 08:23
  • It works! thanks! Last question: do you know if it's possible to show, for each subplot, the number of observations for each embark town? so having like n= number of observation above each embark town? – Stefano Puccini May 27 '21 at 15:17
  • As you can see in the description, the value of the row of the subplot can be displayed by {row_var}, but I don't know if the N number can be displayed. – r-beginners May 28 '21 at 02:26
  • @StefanoPuccini regarding annotation with N=..., scroll down the documentation for seaborn facetgrid, theres an example for annotating :) https://seaborn.pydata.org/generated/seaborn.FacetGrid.html?highlight=facetgrid#seaborn.FacetGrid – TheRibosome Jun 09 '22 at 08:43