Commit 73718362 authored by Mo Shahdloo's avatar Mo Shahdloo Committed by Paul McCarthy
Browse files

seaborn tutorial initial draft

parent 250fc2fc
{
"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. \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",
"\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_theme()"
]
},
{
"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": [
"Now let's see how the distribution of bill length vs depth look like. To do this, we have to pass these parameter names to the `x` and `y` 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": "herbal-combine",
"metadata": {},
"outputs": [],
"source": [
"sns.set_style('whitegrid') # which means white background, and grids on"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "shaped-clinton",
"metadata": {},
"outputs": [],
"source": [
"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": "fuzzy-welsh",
"metadata": {},
"source": [
"paranthesis 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. 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": [
"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, 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\n",
"sns.set_style('ticks')"
]
},
{
"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": "dominant-doctor",
"metadata": {},
"source": [
"It seems that the data could be better delineated in log scale..."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "reported-front",
"metadata": {},
"outputs": [],
"source": [
"g = sns.scatterplot(data=planets, x=\"distance\", y=\"orbital_period\")\n",
"g.set(yscale=\"log\", xscale=\"log\")\n",
"sns.despine()"
]
},
{
"cell_type": "markdown",
"id": "living-nightlife",
"metadata": {},
"source": [
"Seaborn can also plot the marginal distributions, cool!\n",
"To do this, you should first create a `JointGrid` object that consists of a _joint_ axis and two _marginal_ axes, containing the joint distribution and the two marginal distributions. "
]
},
{
"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\", marginal_ticks=True)\n",
"\n",
"# the distance axis 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.histplot, kde=True)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
%% Cell type:markdown id:caring-plate tags:
# Tabular data visualisation using Seaborn
---
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)).
`Seaborn` is a visualisation library built on top of `matplotlib` and provides a convenient user interface to produce various types of plots.
%% Cell type:markdown id:equipped-minnesota tags:
## Contents
---
* [Relative distributions (and basic figure aesthetics)](#scatter)
* [Linear regression](#linear)
* [Data aggregation and uncertainty bounds](#line)
* [Marginal plots](#marginals)
This tutorial relies heavily on the materials provided in the [`seaborn` documentation](https://seaborn.pydata.org/examples/index.html).
%% Cell type:code id:suspected-worthy tags:
``` python
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
sns.set_theme()
```
%% Cell type:markdown id:champion-answer tags:
## Plotting relative distributions
---
<a id='scatter'></a>
Seaborn library provides a couple of `pandas` datsets to explore various plot types. The one we load below is about penguins 🐧
%% Cell type:code id:pressed-individual tags:
``` python
# Load the penguins dataset
penguins = sns.load_dataset("penguins")
```
<