"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",
"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"
"`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"
]
]
},
},
{
{
...
@@ -22,6 +22,7 @@
...
@@ -22,6 +22,7 @@
" * [Linear regression](#linear)\n",
" * [Linear regression](#linear)\n",
"* [Data aggregation and uncertainty bounds](#line)\n",
"* [Data aggregation and uncertainty bounds](#line)\n",
"* [Marginal plots](#marginals)\n",
"* [Marginal plots](#marginals)\n",
"* [Pairwise relationships](#pair)\n",
"\n",
"\n",
"This tutorial relies heavily on the materials provided in the [`seaborn` documentation](https://seaborn.pydata.org/examples/index.html)."
"This tutorial relies heavily on the materials provided in the [`seaborn` documentation](https://seaborn.pydata.org/examples/index.html)."
]
]
...
@@ -77,39 +78,51 @@
...
@@ -77,39 +78,51 @@
"id": "opposite-encounter",
"id": "opposite-encounter",
"metadata": {},
"metadata": {},
"source": [
"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."
"`pandas` itself is able to produce different plots, by assigningthe 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 magnitudes of orders easier.\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",
"\n",
"Seaborn comes with a couple of predefined themes; `darkgrid`, `whitegrid`, `dark`, `white`, `ticks`. \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 make the figure above a bit fancier"
]
]
},
},
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": null,
"execution_count": null,
"id": "herbal-combine",
"id": "placed-egyptian",
"metadata": {},
"metadata": {},
"outputs": [],
"outputs": [],
"source": [
"source": [
"sns.set_style('whitegrid') # which means white background, and grids on"
"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"
]
]
},
},
{
{
...
@@ -119,6 +132,7 @@
...
@@ -119,6 +132,7 @@
"metadata": {},
"metadata": {},
"outputs": [],
"outputs": [],
"source": [
"source": [
"sns.set_style('whitegrid') # which means white background, and grids on\n",
"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. 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."
]
]
},
},
{
{
...
@@ -210,6 +247,8 @@
...
@@ -210,6 +247,8 @@
"metadata": {},
"metadata": {},
"outputs": [],
"outputs": [],
"source": [
"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",
"g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')\n",
"sns.despine()"
"sns.despine()"
...
@@ -232,7 +271,7 @@
...
@@ -232,7 +271,7 @@
"source": [
"source": [
"### Linear regression\n",
"### Linear regression\n",
"<a id='scatter'></a>\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."
"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."
]
]
},
},
{
{
...
@@ -503,8 +542,7 @@
...
@@ -503,8 +542,7 @@
"outputs": [],
"outputs": [],
"source": [
"source": [
"planets = sns.load_dataset(\"planets\")\n",
"planets = sns.load_dataset(\"planets\")\n",
"planets = planets.dropna(subset=['mass', 'distance']) # remove NaN entries\n",
"planets = planets.dropna(subset=['mass', 'distance']) # remove NaN entries"
"sns.set_style('ticks')"
]
]
},
},
{
{
...
@@ -532,31 +570,30 @@
...
@@ -532,31 +570,30 @@
},
},
{
{
"cell_type": "markdown",
"cell_type": "markdown",
"id": "dominant-doctor",
"id": "requested-civilian",
"metadata": {},
"metadata": {},
"source": [
"source": [
"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`"
"Seaborn can also plot the marginal distributions, cool!\n",
"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",
"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. "
"\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."
]
]
},
},
{
{
...
@@ -571,7 +608,7 @@
...
@@ -571,7 +608,7 @@
"# define the JointGrid, and the data corresponding to each axis\n",
"# define the JointGrid, and the data corresponding to each axis\n",
"# plot the joint scatter plot in the joint axis\n",
"# plot the joint scatter plot in the joint axis\n",
...
@@ -581,6 +618,51 @@
...
@@ -581,6 +618,51 @@
"# plot the joint histograms, overlayed with kernel density estimates\n",
"# plot the joint histograms, overlayed with kernel density estimates\n",
"g.plot_marginals(sns.histplot, kde=True)"
"g.plot_marginals(sns.histplot, kde=True)"
]
]
},
{
"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 the 🐧 dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "boolean-mineral",
"metadata": {},
"outputs": [],
"source": [
"sns.pairplot(penguins)"
]
},
{
"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 `hist`, and kernel density estimates in the lowe-diagonal plots 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)).
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.
`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).
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:
%% Cell type:code id:suspected-worthy tags:
``` python
``` python
importseabornassns
importseabornassns
importpandasaspd
importpandasaspd
importmatplotlib.pyplotasplt
importmatplotlib.pyplotasplt
importnumpyasnp
importnumpyasnp
sns.set_theme()
sns.set_theme()
```
```
%% Cell type:markdown id:champion-answer tags:
%% Cell type:markdown id:champion-answer tags:
## Plotting relative distributions
## Plotting relative distributions
---
---
<aid='scatter'></a>
<aid='scatter'></a>
Seaborn library provides a couple of `pandas` datsets to explore various plot types. The one we load below is about penguins 🐧
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:
%% Cell type:code id:pressed-individual tags:
``` python
``` python
# Load the penguins dataset
# Load the penguins dataset
penguins=sns.load_dataset("penguins")
penguins=sns.load_dataset("penguins")
```
```
%% Cell type:code id:elder-corner tags:
%% Cell type:code id:elder-corner tags:
``` python
``` python
penguins
penguins
```
```
%% Cell type:markdown id:opposite-encounter tags:
%% 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.
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.
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.
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`.
Seaborn comes with a couple of predefined themes; `darkgrid`, `whitegrid`, `dark`, `white`, `ticks`.
Let's make the figure above a bit fancier
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:
%% Cell type:code id:shaped-clinton tags:
``` python
``` 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')
g.set(xlabel='Snoot length (mm)',ylabel='Snoot depth (mm)',title='Snoot depth vs length')
sns.despine()
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. 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:
%% Cell type:code id:designed-angle tags:
``` python
``` 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')
g.set(xlabel='Snoot length (mm)',ylabel='Snoot depth (mm)',title='Snoot depth vs length')
sns.despine()
sns.despine()
```
```
%% Cell type:markdown id:fourth-southwest tags:
%% Cell type:markdown id:fourth-southwest tags:
The guess was correct!
The guess was correct!
---
---
%% Cell type:markdown id:parental-dispatch tags:
%% Cell type:markdown id:parental-dispatch tags:
### Linear regression
### Linear regression
<aid='scatter'></a>
<aid='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.
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
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)
g.fig.suptitle('Snoot depth vs length -- 80% CI',y=1.05)
```
```
%% Cell type:markdown id:employed-twenty tags:
%% Cell type:markdown id:employed-twenty tags:
---
---
## Data aggregation and uncertainty bounds
## Data aggregation and uncertainty bounds
<aid='line'></a>
<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.
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.
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.
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`.
Seaborn can also plot the marginal distributions, cool!
`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.
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:
%% Cell type:code id:realistic-batman tags:
``` python
``` python
# define the JointGrid, and the data corresponding to each axis
# define the JointGrid, and the data corresponding to each axis
# plot the joint histograms, overlayed with kernel density estimates
# plot the joint histograms, overlayed with kernel density estimates
g.plot_marginals(sns.histplot,kde=True)
g.plot_marginals(sns.histplot,kde=True)
```
```
%% 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 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`.