Commit e0d4ca81 authored by Paul McCarthy's avatar Paul McCarthy 🚵
Browse files

Merge branch 'seaborn' into 'master'

seaborn tutorial

See merge request fsl/win-pytreat!13
parents 250fc2fc d75f4a5e
{
"cells": [
{
"cell_type": "markdown",
"id": "caring-plate",
"metadata": {},
"source": [
"# Tabular data visualisation using Seaborn\n",
"---\n",
"When it comes to tabular data, one of the best libraries to choose is `pandas` (for an intro to `pandas` see [this tutorial](https://git.fmrib.ox.ac.uk/fsl/win-pytreat/-/blob/fsleyes_branch/applications/pandas/pandas.ipynb)). \n",
"`seaborn` is a visualisation library built on top of `matplotlib` and provides a convenient user interface to produce various types of plots from `pandas` dataframes. \n"
]
},
{
"cell_type": "markdown",
"id": "equipped-minnesota",
"metadata": {},
"source": [
"## Contents\n",
"---\n",
"* [Relative distributions (and basic figure aesthetics)](#scatter)\n",
" * [Linear regression](#linear)\n",
"* [Data aggregation and uncertainty bounds](#line)\n",
"* [Marginal plots](#marginals)\n",
"* [Pairwise relationships](#pair)\n",
"\n",
"This tutorial relies heavily on the materials provided in the [`seaborn` documentation](https://seaborn.pydata.org/examples/index.html)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "suspected-worthy",
"metadata": {},
"outputs": [],
"source": [
"import seaborn as sns\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"sns.set()"
]
},
{
"cell_type": "markdown",
"id": "champion-answer",
"metadata": {},
"source": [
"## Plotting relative distributions\n",
"---\n",
"<a id='scatter'></a>\n",
"Seaborn library provides a couple of `pandas` datsets to explore various plot types. The one we load below is about penguins 🐧 "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "pressed-individual",
"metadata": {},
"outputs": [],
"source": [
"# Load the penguins dataset\n",
"penguins = sns.load_dataset(\"penguins\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "elder-corner",
"metadata": {},
"outputs": [],
"source": [
"penguins"
]
},
{
"cell_type": "markdown",
"id": "opposite-encounter",
"metadata": {},
"source": [
"`pandas` itself is able to produce different plots, by assigning the column names to the horizontal and vertical axes. This makes plotting the data stored in the table easier by using the human-readable strings of column names instead of lazily chosen variable names. Now let's see how the distribution of bill length vs depth look like as a scatter plot. "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "lasting-battlefield",
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"penguins.plot(kind='scatter', x='bill_length_mm', y='bill_depth_mm')"
]
},
{
"cell_type": "markdown",
"id": "significant-behavior",
"metadata": {},
"source": [
"As noted in the beginning, `seaborn` is built on top of `pandas` and `matplotlib`, so everything that is acheivable via `seaborn` is achievable using a -- not so straightforward -- combination of the other two. But the magic of `seaborn` is that it makes the job of producing various publication-quality figures orders of magnitude easier.\n",
"\n",
"Let's start by plotting the same scatterplot, but this time via `seaborn`. To do this, we have to pass the names of columns of interest to the `x` and `y` parameters corresponding to the horizontal and vertical axes."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "placed-egyptian",
"metadata": {},
"outputs": [],
"source": [
"g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')"
]
},
{
"cell_type": "markdown",
"id": "intensive-citizenship",
"metadata": {},
"source": [
"---\n",
"Let's open a large paranthesis here and explore some of the parameters that control figure aesthetics. We will later return to explore different plot types.\n",
"\n",
"Seaborn comes with a couple of predefined themes; `darkgrid`, `whitegrid`, `dark`, `white`, `ticks`. \n",
"Let's make the figure above a bit fancier"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "shaped-clinton",
"metadata": {},
"outputs": [],
"source": [
"sns.set_style('whitegrid') # which means white background, and grids on\n",
"g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')"
]
},
{
"cell_type": "markdown",
"id": "sealed-egyptian",
"metadata": {},
"source": [
"other styles look like this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "regular-oriental",
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"for style in ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']:\n",
" sns.set_style(style)\n",
" g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"id": "eleven-librarian",
"metadata": {},
"source": [
"To remove the top and right axis spines in the `white`, `whitegrid`, and `tick` themes you can call the `despine()` function"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cosmetic-event",
"metadata": {},
"outputs": [],
"source": [
"sns.set_style('white')\n",
"g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')\n",
"sns.despine()"
]
},
{
"cell_type": "markdown",
"id": "laughing-islam",
"metadata": {},
"source": [
"Axes labels can also be set to something human-readable, and making the markers larger makes the figure nicer..."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "seven-allergy",
"metadata": {},
"outputs": [],
"source": [
"g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', s=80)\n",
"g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')\n",
"sns.despine()"
]
},
{
"cell_type": "markdown",
"id": "textile-south",
"metadata": {},
"source": [
"One of the handy features of `seaborn` is that it can automatically adjust your figure properties according to the _context_ it is going to be used: `notebook`(default), `paper`, `talk`, and `poster`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "timely-brazil",
"metadata": {},
"outputs": [],
"source": [
"for context in ['notebook', 'paper', 'talk', 'poster']:\n",
" sns.set_context(context)\n",
" g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')\n",
" g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')\n",
" sns.despine()\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"id": "fuzzy-welsh",
"metadata": {},
"source": [
"parenthesis closed.\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"id": "architectural-corruption",
"metadata": {},
"source": [
"It seems that there are separate clusters in the data. A reasonable guess could be that the clusters correspond to different penguin species. To test this, we can color each dot based on a categorical variable (e.g., species) using the `hue` parameter."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "designed-angle",
"metadata": {},
"outputs": [],
"source": [
"sns.set_context('notebook') # set the context used for the subsequecnt plots\n",
"\n",
"g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', hue='species', s=80)\n",
"g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')\n",
"sns.despine()"
]
},
{
"cell_type": "markdown",
"id": "fourth-southwest",
"metadata": {},
"source": [
"The guess was correct!\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"id": "parental-dispatch",
"metadata": {},
"source": [
"### Linear regression\n",
"<a id='scatter'></a>\n",
"There also seems to be a linear dependece between the two parameters, separately in each species. A linear fit to the data can be easily plotted by using `lmplot` which is a convenient shortcut to `scatterplot` with extra features for linear regression."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "protecting-oracle",
"metadata": {},
"outputs": [],
"source": [
"g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', \n",
" hue='species', \n",
" scatter_kws={\"s\": 60})\n",
"g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')"
]
},
{
"cell_type": "markdown",
"id": "brave-equilibrium",
"metadata": {},
"source": [
"Note that since `lmplot` is derived from `scatterplot` any extra arguments used by `scatterplot` should be passed via `scatter_kws` parameter."
]
},
{
"cell_type": "markdown",
"id": "simple-tradition",
"metadata": {},
"source": [
"Alternatively, we could plot the data for each species in a separate column by setting `col` "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "robust-organizer",
"metadata": {},
"outputs": [],
"source": [
"g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', \n",
" hue='species',\n",
" col='species',\n",
" scatter_kws={\"s\": 60})\n",
"g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)')\n",
"g.fig.suptitle('Snoot depth vs length', y=1.05)"
]
},
{
"cell_type": "markdown",
"id": "prospective-mason",
"metadata": {},
"source": [
"The confidence bounds shown above are calculated based on standard deviation by default. Alternatively confidence interval can be used by specifying the confidence interval percentage"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bored-roulette",
"metadata": {},
"outputs": [],
"source": [
"g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', \n",
" hue='species',\n",
" col='species', \n",
" ci=80,\n",
" scatter_kws={\"s\": 60})\n",
"g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)')\n",
"g.fig.suptitle('Snoot depth vs length -- 80% CI', y=1.05)"
]
},
{
"cell_type": "markdown",
"id": "employed-twenty",
"metadata": {},
"source": [
"---\n",
"\n",
"## Data aggregation and uncertainty bounds\n",
"<a id='line'></a>\n",
"\n",
"In some datasets, repetitive measurements for example, there might be multiple values from one variable corresponding to each instance from the other variable. To explore an instance of such data, lets load the `fmri` dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "south-entrance",
"metadata": {},
"outputs": [],
"source": [
"sns.set_style('ticks')\n",
"fmri = sns.load_dataset(\"fmri\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "interracial-hello",
"metadata": {},
"outputs": [],
"source": [
"fmri"
]
},
{
"cell_type": "markdown",
"id": "exclusive-yahoo",
"metadata": {},
"source": [
"Lets visualise the signal values across time..."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "choice-isaac",
"metadata": {},
"outputs": [],
"source": [
"g = sns.scatterplot(x=\"timepoint\", y=\"signal\", data=fmri)\n",
"sns.despine()"
]
},
{
"cell_type": "markdown",
"id": "interesting-possession",
"metadata": {},
"source": [
"To plot the mean signal versus time we can use the `relplot` "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "infrared-remainder",
"metadata": {},
"outputs": [],
"source": [
"sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, ci=None)"
]
},
{
"cell_type": "markdown",
"id": "digital-sheriff",
"metadata": {},
"source": [
"By default, mean of the signal at each `x` instance is plotted. But any arbitrary function could also be used to aggregate the data. For instance, we could use the `median` function from `numpy` package to calculate the value corresponding to each timepoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "interesting-pizza",
"metadata": {},
"outputs": [],
"source": [
"sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, ci=None, estimator=np.median)"
]
},
{
"cell_type": "markdown",
"id": "medium-editing",
"metadata": {},
"source": [
"Overlaying the uncertainty bounds is easily achievable by specifying the confidence interval percentage."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "demographic-video",
"metadata": {},
"outputs": [],
"source": [
"sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, ci=95, estimator=np.median)"
]
},
{
"cell_type": "markdown",
"id": "deluxe-hacker",
"metadata": {},
"source": [
" Standard deviation could also be used instead"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "touched-technical",
"metadata": {},
"outputs": [],
"source": [
"sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, ci='sd', estimator=np.median)"
]
},
{
"cell_type": "markdown",
"id": "fantastic-ghost",
"metadata": {},
"source": [
"Similar to any other plot type in `seaborn`, data with different semantics can be separately plotted by assigning them to `hue`, `col`, or `style` parameters. Let's separately plot the data for the _parietal_ and _frontal_ regions."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "better-imperial",
"metadata": {},
"outputs": [],
"source": [
"sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, hue='region')"
]
},
{
"cell_type": "markdown",
"id": "silent-messenger",
"metadata": {},
"source": [
"or we could separate them even more detailed, based on the event type; _cue_ or _stimulus_"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "regional-exhaust",
"metadata": {},
"outputs": [],
"source": [
"sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, hue='region', style='event')"
]
},
{
"cell_type": "markdown",
"id": "incorporated-blackjack",
"metadata": {},
"source": [
"we can also plot each event in a separate subplot"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "spectacular-stranger",
"metadata": {},
"outputs": [],
"source": [
"sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, hue='region', col='event')"
]
},
{
"cell_type": "markdown",
"id": "seeing-wages",
"metadata": {},
"source": [
"---\n",
"\n",
"## Marginal distributions\n",
"<a id='marginals'></a>\n",
"\n",
"Let's load a larger dataset; some measurements on planets 🪐 "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "incomplete-county",
"metadata": {},
"outputs": [],
"source": [
"planets = sns.load_dataset(\"planets\")\n",
"planets = planets.dropna(subset=['mass', 'distance']) # remove NaN entries"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "abandoned-frequency",
"metadata": {},
"outputs": [],
"source": [
"planets"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "czech-terminology",
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"g = sns.scatterplot(data=planets, x=\"distance\", y=\"orbital_period\")\n",
"sns.despine()"
]
},
{
"cell_type": "markdown",
"id": "requested-civilian",
"metadata": {},
"source": [
"`seaborn` can also plot the marginal distributions, cool! To do this, we can use `jointplot`"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "environmental-willow",
"metadata": {},
"outputs": [],
"source": [
"g = sns.jointplot(data=planets, x=\"distance\", y=\"orbital_period\")"
]
},
{
"cell_type": "markdown",
"id": "dominant-doctor",
"metadata": {},
"source": [
"However, it seems that the data could be better delineated in log scale... but `jointplot` is not flexible enough to do so. The solution is to go one level higher and build the figure we need using `JointGrid`. \n",
"\n",
"`JointGrid` creates a _joint axis_ that hosts the jont distribution of the two variables and two _marginal axes_ that hosts the two marginal distributions. Each of these axes can show almost any of the plots available in `seaborn`, and they provide access to many detailed plot tweaks."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "realistic-batman",
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"# define the JointGrid, and the data corresponding to each axis\n",
"g = sns.JointGrid(data=planets, x=\"distance\", y=\"orbital_period\")\n",
"\n",
"# the axes should be log-scaled!\n",
"g.ax_joint.set(yscale=\"log\", xscale=\"log\")\n",
"\n",
"# plot the joint scatter plot in the joint axis\n",
"# Heavier planets are marked with larger dots, and `sizes` controls the range of marker sizes\n",
"g.plot_joint(sns.scatterplot, size=planets.mass, sizes=(10, 200))\n",
"\n",
"# plot the joint histograms, overlayed with kernel density estimates\n",
"g.plot_marginals(sns.distplot, kde=False, \n",
" bins=np.logspace(np.log10(1),np.log10(5000), 30))"
]
},
{
"cell_type": "markdown",
"id": "restricted-damages",
"metadata": {},
"source": [
"---\n",
"\n",
"## Pairwise relationships\n",
"<a id='pair'></a>\n",
"\n",
"`seaborn` also provides a convenient tool to have an overview of the relationships among each pair of the columns in a large table using `pairplot`. This could hint to potential dependencies among variables.\n",
"\n",
"Lets see the overview of the pairwise relationships in a dataset that contains the data on iris flowers 🌸."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fancy-trial",
"metadata": {},
"outputs": [],
"source": [
"iris = sns.load_dataset('iris')"
]
},
{
"cell_type": "code",