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

pairwise plots added

and few minor adjustments
parent 73718362
%% 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.
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 from `pandas` dataframes.
%% 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)
* [Pairwise relationships](#pair)
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:
......@@ -47,11 +48,23 @@
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.
`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 id:lasting-battlefield tags:
``` python
penguins.plot(kind='scatter', x='bill_length_mm', y='bill_depth_mm')
```
%% Cell type:markdown id:significant-behavior tags:
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 magnitudes of orders easier.
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 id:placed-egyptian tags:
``` python
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
......@@ -63,19 +76,14 @@
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
sns.set_style('whitegrid') # which means white background, and grids on
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
```
%% Cell type:markdown id:sealed-egyptian tags:
......@@ -112,23 +120,40 @@
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:textile-south tags:
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 id:timely-brazil tags:
``` python
for context in ['notebook', 'paper', 'talk', 'poster']:
sns.set_context(context)
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')
sns.despine()
plt.show()
```
%% 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.
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 id:designed-angle tags:
``` python
sns.set_context('notebook') # set the context used for the subsequecnt plots
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()
```
......@@ -140,11 +165,11 @@
%% 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.
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 id:protecting-oracle tags:
``` python
g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm',
......@@ -303,11 +328,10 @@
%% 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
......@@ -319,38 +343,66 @@
``` python
g = sns.scatterplot(data=planets, x="distance", y="orbital_period")
sns.despine()
```
%% Cell type:markdown id:dominant-doctor tags:
%% Cell type:markdown id:requested-civilian tags:
It seems that the data could be better delineated in log scale...
`seaborn` can also plot the marginal distributions, cool! To do this, we can use `jointplot`
%% Cell type:code id:reported-front tags:
%% Cell type:code id:environmental-willow tags:
``` python
g = sns.scatterplot(data=planets, x="distance", y="orbital_period")
g.set(yscale="log", xscale="log")
sns.despine()
g = sns.jointplot(data=planets, x="distance", y="orbital_period")
```
%% Cell type:markdown id:living-nightlife tags:
%% Cell type:markdown id:dominant-doctor tags:
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`.
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.
`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 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!
# the axes 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)
```
%% Cell type:markdown id:restricted-damages tags:
---
## Pairwise relationships
<a id='pair'></a>
`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.
Lets see the overview of the pairwise relationships in the 🐧 dataset.
%% Cell type:code id:boolean-mineral tags:
``` python
sns.pairplot(penguins)
```
%% Cell type:markdown id:pressed-clone tags:
By default, scatterplots are used to show the distribution of each pair, and histograms of marginal distributions are shown on the diagonal. Note, however, that the upper-diagonal, lower-diagonal, and diagonal plots can be modified independently. For instance, we can plot the linear regression lines in the upper-diagonal plots using `regplot`, marginal histograms on the diagonals using `hist`, and kernel density estimates in the lowe-diagonal plots using `kdeplot`.
%% Cell type:code id:rocky-education tags:
``` python
g = sns.pairplot(penguins, diag_kind="hist")
g.map_lower(sns.kdeplot, levels=4, color="green")
g.map_upper(sns.regplot, line_kws={"color": "red"})
```
......
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