"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"
"* [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. "
"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."
"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.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",
"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",
"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."
"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"
"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."
"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."
"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."
"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",
"`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",
"execution_count": null,
"id": "medium-department",
"metadata": {},
"outputs": [],
"source": [
"iris"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "boolean-mineral",
"metadata": {},
"outputs": [],
"source": [
"sns.pairplot(iris)"
]
},
{
"cell_type": "markdown",
"id": "pressed-clone",
"metadata": {},
"source": [
"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 `kdeplot`, and kernel density estimates in the lower-diagonal plots also using `kdeplot`."
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.
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
importseabornassns
importpandasaspd
importmatplotlib.pyplotasplt
importnumpyasnp
sns.set()
```
%% Cell type:markdown id:champion-answer tags:
## Plotting relative distributions
---
<aid='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:
`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.
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.
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.
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:shaped-clinton tags:
``` python
sns.set_style('whitegrid')# which means white background, and grids on
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`.
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.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
<aid='scatter'></a>
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.
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
g.fig.suptitle('Snoot depth vs length -- 80% CI',y=1.05)
```
%% Cell type:markdown id:employed-twenty tags:
---
## Data aggregation and uncertainty bounds
<aid='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.
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.
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.
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`.
`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
# plot the joint histograms, overlayed with kernel density estimates
g.plot_marginals(sns.distplot,kde=False,
bins=np.logspace(np.log10(1),np.log10(5000),30))
```
%% Cell type:markdown id:restricted-damages tags:
---
## Pairwise relationships
<aid='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 a dataset that contains the data on iris flowers 🌸.
%% Cell type:code id:fancy-trial tags:
``` python
iris=sns.load_dataset('iris')
```
%% Cell type:code id:medium-department tags:
``` python
iris
```
%% Cell type:code id:boolean-mineral tags:
``` python
sns.pairplot(iris)
```
%% 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 `kdeplot`, and kernel density estimates in the lower-diagonal plots also using `kdeplot`.