Statistical annotations on plots

Required packages

The required package for this section is statannotations, which will also automatically install the pandas and seaborn packages, on which it is dependent. As of statannotations version 0.6, it unfortunately relies on outdated versions of pandas and seaborn. These can be installed with the following command in the command window (Windows) / terminal (Mac).

pip install statannotations

On Windows systems, the above command to install statannotations may give an error stating that the building of the wheels has failed. To fix this error the Visual studio C++ build tools have to be installed. You can use this installer and check the options as shown in the screenshot below:

After the installation has completed run the following commands in the terminal:

pip install --upgrade setuptools
pip install statannotations

The statsannotations library should now have installed correctly.

Loading the data

We will again use the demo lipidomics dataset:

Load the dataset into a Pandas DataFrame named df as described in the basic plotting section:

import pandas as pd
df = pd.read_excel("Lipidomics_dataset.xlsx")
df.set_index("Sample Name", inplace=True)

Boxplots

To get the annotations of a statistical test drawn automatically on a plot, the statsanotations package can be used in combination with seaborn. We'll have to define, which column of our dataframe contains the x-axis variable (the "Label" column), and the y-variable is the lipid species of choice. We'll define the order in which we want the different "Label" groups to appear and which pairs we want to compare. Finally we'll also pass to the configurator which statistical test we want to use, Mann-Whitney in this case:

import seaborn as sns
from statannotations.Annotator import Annotator
import matplotlib.pyplot as plt

x = "Label"
y = "PC 36:5"
order = ['N', 'PAN', 'T']
pairs = [("N", "PAN"), ("N", "T"), ("PAN", "T")]
ax = sns.boxplot(data=df, x=x, y=y, order=order)
annot = Annotator(ax, pairs=pairs, data=df, x=x, y=y, order=order)
annot.configure(test='Mann-Whitney', loc='inside')
annot.apply_test()
annot.annotate()
plt.show()

Last updated