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

seaborn tutorial initial draft

parent 250fc2fc
%% 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")
```
%% Cell type:code id:elder-corner tags:
``` python
penguins
```
%% Cell type:markdown id:opposite-encounter tags:
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 id:placed-egyptian tags:
``` python
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
```
%% Cell type:markdown id:intensive-citizenship tags:
---
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.
Seaborn comes with a couple of predefined themes; `darkgrid`, `whitegrid`, `dark`, `white`, `ticks`.
Let's make the figure above a bit fancier
%% Cell type:code id:herbal-combine tags:
``` python
sns.set_style('whitegrid') # which means white background, and grids on
```
%% Cell type:code id:shaped-clinton tags:
``` python
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
```
%% Cell type:markdown id:sealed-egyptian tags:
other styles look like this:
%% Cell type:code id:regular-oriental tags:
``` python
for style in ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']:
sns.set_style(style)
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
plt.show()
```
%% Cell type:markdown id:eleven-librarian tags:
To remove the top and right axis spines in the `white`, `whitegrid`, and `tick` themes you can call the `despine()` function
%% Cell type:code id:cosmetic-event tags:
``` python
sns.set_style('white')
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
sns.despine()
```
%% Cell type:markdown id:laughing-islam tags:
Axes labels can also be set to something human-readable, and making the markers larger makes the figure nicer...
%% Cell type:code id:seven-allergy tags:
``` python
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', s=80)
g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')
sns.despine()
```
%% Cell type:markdown id:fuzzy-welsh tags:
paranthesis closed.
---
%% Cell type:markdown id:architectural-corruption tags:
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 id:designed-angle tags:
``` python
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', hue='species', s=80)
g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')
sns.despine()
```
%% Cell type:markdown id:fourth-southwest tags:
The guess was correct!
---
%% Cell type:markdown id:parental-dispatch tags:
### Linear regression
<a id='scatter'></a>
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 id:protecting-oracle tags:
``` python
g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm',
hue='species',
scatter_kws={"s": 60})
g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')
```
%% Cell type:markdown id:brave-equilibrium tags:
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 tags:
Alternatively, we could plot the data for each species in a separate column by setting `col`
%% Cell type:code id:robust-organizer tags:
``` python
g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm',
hue='species',
col='species',
scatter_kws={"s": 60})
g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)')
g.fig.suptitle('Snoot depth vs length', y=1.05)
```
%% Cell type:markdown id:prospective-mason tags:
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 id:bored-roulette tags:
``` python
g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm',
hue='species',
col='species',
ci=80,
scatter_kws={"s": 60})
g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)')
g.fig.suptitle('Snoot depth vs length -- 80% CI', y=1.05)
```
%% Cell type:markdown id:employed-twenty tags:
---
## Data aggregation and uncertainty bounds
<a id='line'></a>
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 id:south-entrance tags:
``` python
sns.set_style('ticks')
fmri = sns.load_dataset("fmri")
```
%% Cell type:code id:interracial-hello tags:
``` python
fmri
```
%% Cell type:markdown id:exclusive-yahoo tags:
Lets visualise the signal values across time...
%% Cell type:code id:choice-isaac tags:
``` python
g = sns.scatterplot(x="timepoint", y="signal", data=fmri)
sns.despine()
```
%% Cell type:markdown id:interesting-possession tags:
To plot the mean signal versus time we can use the `relplot`
%% Cell type:code id:infrared-remainder tags:
``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=None)
```
%% Cell type:markdown id:digital-sheriff tags:
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 id:interesting-pizza tags:
``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=None, estimator=np.median)
```
%% Cell type:markdown id:medium-editing tags:
Overlaying the uncertainty bounds is easily achievable by specifying the confidence interval percentage.
%% Cell type:code id:demographic-video tags:
``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=95, estimator=np.median)
```
%% Cell type:markdown id:deluxe-hacker tags:
Standard deviation could also be used instead
%% Cell type:code id:touched-technical tags:
``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci='sd', estimator=np.median)
```
%% Cell type:markdown id:fantastic-ghost tags:
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 id:better-imperial tags:
``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region')
```
%% Cell type:markdown id:silent-messenger tags:
or we could separate them even more detailed, based on the event type; _cue_ or _stimulus_
%% Cell type:code id:regional-exhaust tags:
``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region', style='event')
```
%% Cell type:markdown id:incorporated-blackjack tags:
we can also plot each event in a separate subplot
%% Cell type:code id:spectacular-stranger tags:
``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region', col='event')
```
%% Cell type:markdown id:seeing-wages tags:
---
## Marginal distributions
<a id='marginals'></a>
Let's load a larger dataset; some measurements on planets 🪐
%% Cell type:code id:incomplete-county tags:
``` python
planets = sns.load_dataset("planets")
planets = planets.dropna(subset=['mass', 'distance']) # remove NaN entries
sns.set_style('ticks')
```
%% Cell type:code id:abandoned-frequency tags:
``` python
planets
```
%% Cell type:code id:czech-terminology tags:
``` python
g = sns.scatterplot(data=planets, x="distance", y="orbital_period")
sns.despine()
```
%% Cell type:markdown id:dominant-doctor tags:
It seems that the data could be better delineated in log scale...
%% Cell type:code id:reported-front tags:
``` python
g = sns.scatterplot(data=planets, x="distance", y="orbital_period")
g.set(yscale="log", xscale="log")
sns.despine()
```
%% Cell type:markdown id:living-nightlife tags:
Seaborn can also plot the marginal distributions, cool!
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 id:realistic-batman tags:
``` python
# define the JointGrid, and the data corresponding to each axis
g = sns.JointGrid(data=planets, x="distance", y="orbital_period", marginal_ticks=True)
# the distance axis should be log-scaled!
g.ax_joint.set(yscale="log", xscale="log")
# plot the joint scatter plot in the joint axis
# Heavier planets are marked with larger dots, and `sizes` controls the range of marker sizes
g.plot_joint(sns.scatterplot, size=planets.mass, sizes=(10, 200))
# plot the joint histograms, overlayed with kernel density estimates
g.plot_marginals(sns.histplot, kde=True)
```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment