Home > Software design >  How does one insert statistical annotations (e.g. p-values) into a seaboarn figure-level plot (e.g.
How does one insert statistical annotations (e.g. p-values) into a seaboarn figure-level plot (e.g.

Time:02-07

Goal: Given a seaborn catplot (kind="bar") with multiple rows, grouped bars, and a mapped stripplot, how do I add statistical annotations (p-values).

The following code from Catplot without statistical annotation


What I tried: I tried to use statannotations.Annotator.Annotator.plot_and_annotate_facets(). However, I was not able to get it working properly.

I also tried to use statannotations.Annotator.Annotator.new_plot(). However, this just worked for barplots but not for catplots. This is the corresponding code based on Statistical annotation for a barplot

Question: Does anyone know how to insert statistical annotation into a figure-level plot, preferably a catplot (kind="bar")?

CodePudding user response:

I think you can just iterate over the axes in the FacetGrid and apply the Annotator element wise.

Here is a short example with your provided code:

import seaborn as sns
from statannotations.Annotator import Annotator
%matplotlib inline


tips = sns.load_dataset("tips")

args = dict(x="sex", y="total_bill", data=tips, hue="smoker", hue_order=["Yes","No"], order=['Male', 'Female'])

g = sns.catplot(edgecolor="black", errcolor="black", errwidth=1.5, capsize = 0.1, height=4, aspect=.7,alpha=0.5, kind="bar", ci = "sd", row="time", **args)
g.map(sns.stripplot, args["x"], args["y"], args["hue"], hue_order=args["hue_order"], order=args["order"], palette=sns.color_palette(), dodge=True, alpha=0.6, ec='k', linewidth=1)

pairs = [
    (("Male", "Yes"), ("Male", "No")),
    (("Female", "Yes"), ("Female", "No"))
]

for ax_n in g.axes:
    for ax in ax_n:
        annot = Annotator(ax, pairs, **args)
        annot.configure(test='Mann-Whitney', text_format='simple', loc='inside', verbose=2)
        annot.apply_test().annotate()

This produces the following plot:
Plot with annotations

  •  Tags:  
  • Related