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

magnitude’s’

parent f70deab1
...@@ -98,7 +98,7 @@ ...@@ -98,7 +98,7 @@
"id": "significant-behavior", "id": "significant-behavior",
"metadata": {}, "metadata": {},
"source": [ "source": [
"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 magnitudes easier.\n", "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", "\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 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:markdown id:caring-plate tags: %% Cell type:markdown id:caring-plate tags:
# Tabular data visualisation using Seaborn # 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)). 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. `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: %% Cell type:markdown id:equipped-minnesota tags:
## Contents ## Contents
--- ---
* [Relative distributions (and basic figure aesthetics)](#scatter) * [Relative distributions (and basic figure aesthetics)](#scatter)
* [Linear regression](#linear) * [Linear regression](#linear)
* [Data aggregation and uncertainty bounds](#line) * [Data aggregation and uncertainty bounds](#line)
* [Marginal plots](#marginals) * [Marginal plots](#marginals)
* [Pairwise relationships](#pair) * [Pairwise relationships](#pair)
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
import seaborn as sns import seaborn as sns
import pandas as pd import pandas as pd
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
sns.set() sns.set()
``` ```
%% Cell type:markdown id:champion-answer tags: %% Cell type:markdown id:champion-answer tags:
## Plotting relative distributions ## Plotting relative distributions
--- ---
<a id='scatter'></a> <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 🐧 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:
`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. `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: %% Cell type:code id:lasting-battlefield tags:
``` python ``` python
penguins.plot(kind='scatter', x='bill_length_mm', y='bill_depth_mm') penguins.plot(kind='scatter', x='bill_length_mm', y='bill_depth_mm')
``` ```
%% Cell type:markdown id:significant-behavior tags: %% 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 orders of magnitudes easier. 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 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: %% Cell type:code id:placed-egyptian tags:
``` python ``` python
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm') g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
``` ```
%% Cell type:markdown id:intensive-citizenship tags: %% 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. 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:shaped-clinton tags: %% Cell type:code id:shaped-clinton tags:
``` python ``` python
sns.set_style('whitegrid') # which means white background, and grids on sns.set_style('whitegrid') # which means white background, and grids on
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm') g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
``` ```
%% Cell type:markdown id:sealed-egyptian tags: %% Cell type:markdown id:sealed-egyptian tags:
other styles look like this: other styles look like this:
%% Cell type:code id:regular-oriental tags: %% Cell type:code id:regular-oriental tags:
``` python ``` python
for style in ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']: for style in ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']:
sns.set_style(style) sns.set_style(style)
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm') g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
plt.show() plt.show()
``` ```
%% Cell type:markdown id:eleven-librarian tags: %% 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 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: %% Cell type:code id:cosmetic-event tags:
``` python ``` python
sns.set_style('white') sns.set_style('white')
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm') g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
sns.despine() sns.despine()
``` ```
%% Cell type:markdown id:laughing-islam tags: %% 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... 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: %% Cell type:code id:seven-allergy tags:
``` python ``` python
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', s=80) 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') 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: %% 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`. 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: %% Cell type:code id:timely-brazil tags:
``` python ``` python
for context in ['notebook', 'paper', 'talk', 'poster']: for context in ['notebook', 'paper', 'talk', 'poster']:
sns.set_context(context) sns.set_context(context)
g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm') 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') g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')
sns.despine() sns.despine()
plt.show() plt.show()
``` ```
%% Cell type:markdown id:fuzzy-welsh tags: %% Cell type:markdown id:fuzzy-welsh tags:
parenthesis closed. parenthesis closed.
--- ---
%% Cell type:markdown id:architectural-corruption tags: %% 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. To test this, 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 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 = 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') 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
<a id='scatter'></a> <a id='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. 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: %% Cell type:code id:protecting-oracle tags:
``` python ``` python
g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm',
hue='species', hue='species',
scatter_kws={"s": 60}) scatter_kws={"s": 60})
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')
``` ```
%% Cell type:markdown id:brave-equilibrium tags: %% 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. 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: %% Cell type:markdown id:simple-tradition tags:
Alternatively, we could plot the data for each species in a separate column by setting `col` Alternatively, we could plot the data for each species in a separate column by setting `col`
%% Cell type:code id:robust-organizer tags: %% Cell type:code id:robust-organizer tags:
``` python ``` python
g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm',
hue='species', hue='species',
col='species', col='species',
scatter_kws={"s": 60}) scatter_kws={"s": 60})
g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)') g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)')
g.fig.suptitle('Snoot depth vs length', y=1.05) g.fig.suptitle('Snoot depth vs length', y=1.05)
``` ```
%% Cell type:markdown id:prospective-mason tags: %% 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 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: %% Cell type:code id:bored-roulette tags:
``` python ``` python
g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm',
hue='species', hue='species',
col='species', col='species',
ci=80, ci=80,
scatter_kws={"s": 60}) scatter_kws={"s": 60})
g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)') g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)')
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
<a id='line'></a> <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. 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: %% Cell type:code id:south-entrance tags:
``` python ``` python
sns.set_style('ticks') sns.set_style('ticks')
fmri = sns.load_dataset("fmri") fmri = sns.load_dataset("fmri")
``` ```
%% Cell type:code id:interracial-hello tags: %% Cell type:code id:interracial-hello tags:
``` python ``` python
fmri fmri
``` ```
%% Cell type:markdown id:exclusive-yahoo tags: %% Cell type:markdown id:exclusive-yahoo tags:
Lets visualise the signal values across time... Lets visualise the signal values across time...
%% Cell type:code id:choice-isaac tags: %% Cell type:code id:choice-isaac tags:
``` python ``` python
g = sns.scatterplot(x="timepoint", y="signal", data=fmri) g = sns.scatterplot(x="timepoint", y="signal", data=fmri)
sns.despine() sns.despine()
``` ```
%% Cell type:markdown id:interesting-possession tags: %% Cell type:markdown id:interesting-possession tags:
To plot the mean signal versus time we can use the `relplot` To plot the mean signal versus time we can use the `relplot`
%% Cell type:code id:infrared-remainder tags: %% Cell type:code id:infrared-remainder tags:
``` python ``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=None) sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=None)
``` ```
%% Cell type:markdown id:digital-sheriff tags: %% 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. 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: %% Cell type:code id:interesting-pizza tags:
``` python ``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=None, estimator=np.median) sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=None, estimator=np.median)
``` ```
%% Cell type:markdown id:medium-editing tags: %% Cell type:markdown id:medium-editing tags:
Overlaying the uncertainty bounds is easily achievable by specifying the confidence interval percentage. Overlaying the uncertainty bounds is easily achievable by specifying the confidence interval percentage.
%% Cell type:code id:demographic-video tags: %% Cell type:code id:demographic-video tags:
``` python ``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=95, estimator=np.median) sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci=95, estimator=np.median)
``` ```
%% Cell type:markdown id:deluxe-hacker tags: %% Cell type:markdown id:deluxe-hacker tags:
Standard deviation could also be used instead Standard deviation could also be used instead
%% Cell type:code id:touched-technical tags: %% Cell type:code id:touched-technical tags:
``` python ``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci='sd', estimator=np.median) sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, ci='sd', estimator=np.median)
``` ```
%% Cell type:markdown id:fantastic-ghost tags: %% 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. 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: %% Cell type:code id:better-imperial tags:
``` python ``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region') sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region')
``` ```
%% Cell type:markdown id:silent-messenger tags: %% Cell type:markdown id:silent-messenger tags:
or we could separate them even more detailed, based on the event type; _cue_ or _stimulus_ or we could separate them even more detailed, based on the event type; _cue_ or _stimulus_
%% Cell type:code id:regional-exhaust tags: %% Cell type:code id:regional-exhaust tags:
``` python ``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region', style='event') sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region', style='event')
``` ```
%% Cell type:markdown id:incorporated-blackjack tags: %% Cell type:markdown id:incorporated-blackjack tags:
we can also plot each event in a separate subplot we can also plot each event in a separate subplot
%% Cell type:code id:spectacular-stranger tags: %% Cell type:code id:spectacular-stranger tags:
``` python ``` python
sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region', col='event') sns.relplot(x="timepoint", y="signal", kind="line", data=fmri, hue='region', col='event')
``` ```
%% Cell type:markdown id:seeing-wages tags: %% Cell type:markdown id:seeing-wages tags:
--- ---
## Marginal distributions ## Marginal distributions
<a id='marginals'></a> <a id='marginals'></a>
Let's load a larger dataset; some measurements on planets 🪐 Let's load a larger dataset; some measurements on planets 🪐
%% Cell type:code id:incomplete-county tags: %% Cell type:code id:incomplete-county tags:
``` python ``` python
planets = sns.load_dataset("planets") planets = sns.load_dataset("planets")
planets = planets.dropna(subset=['mass', 'distance']) # remove NaN entries planets = planets.dropna(subset=['mass', 'distance']) # remove NaN entries
``` ```
%% Cell type:code id:abandoned-frequency tags: %% Cell type:code id:abandoned-frequency tags:
``` python ``` python
planets planets
``` ```
%% Cell type:code id:czech-terminology tags: %% Cell type:code id:czech-terminology tags:
``` python ``` python
g = sns.scatterplot(data=planets, x="distance", y="orbital_period") g = sns.scatterplot(data=planets, x="distance", y="orbital_period")
sns.despine() sns.despine()
``` ```
%% Cell type:markdown id:requested-civilian tags: %% Cell type:markdown id:requested-civilian tags:
`seaborn` can also plot the marginal distributions, cool! To do this, we can use `jointplot` `seaborn` can also plot the marginal distributions, cool! To do this, we can use `jointplot`
%% Cell type:code id:environmental-willow tags: %% Cell type:code id:environmental-willow tags:
``` python ``` python
g = sns.jointplot(data=planets, x="distance", y="orbital_period") g = sns.jointplot(data=planets, x="distance", y="orbital_period")
``` ```
%% Cell type:markdown id:dominant-doctor 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`. 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. `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: %% 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
g = sns.JointGrid(data=planets, x="distance", y="orbital_period") g = sns.JointGrid(data=planets, x="distance", y="orbital_period")
# the axes should be log-scaled! # the axes should be log-scaled!
g.ax_joint.set(yscale="log", xscale="log") g.ax_joint.set(yscale="log", xscale="log")
# plot the joint scatter plot in the joint axis # plot the joint scatter plot in the joint axis
# Heavier planets are marked with larger dots, and `sizes` controls the range of marker sizes # 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)) g.plot_joint(sns.scatterplot, size=planets.mass, sizes=(10, 200))
# plot the joint histograms, overlayed with kernel density estimates # plot the joint histograms, overlayed with kernel density estimates
g.plot_marginals(sns.distplot, kde=False, g.plot_marginals(sns.distplot, kde=False,
bins=np.logspace(np.log10(1),np.log10(5000), 30)) bins=np.logspace(np.log10(1),np.log10(5000), 30))
``` ```
%% Cell type:markdown id:restricted-damages tags: %% Cell type:markdown id:restricted-damages tags:
--- ---
## Pairwise relationships ## Pairwise relationships
<a id='pair'></a> <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. `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 🌸. 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: %% Cell type:code id:fancy-trial tags:
``` python ``` python
iris = sns.load_dataset('iris') iris = sns.load_dataset('iris')
``` ```
%% Cell type:code id:medium-department tags: %% Cell type:code id:medium-department tags:
``` python ``` python
iris iris
``` ```
%% Cell type:code id:boolean-mineral tags: %% Cell type:code id:boolean-mineral tags:
``` python ``` python
sns.pairplot(iris) sns.pairplot(iris)
``` ```
%% Cell type:markdown id:pressed-clone tags: %% 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`. 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`.
%% Cell type:code id:rocky-education tags: %% Cell type:code id:rocky-education tags:
``` python ``` python
g = sns.PairGrid(iris, diag_sharey=False) g = sns.PairGrid(iris, diag_sharey=False)
g.map_upper(sns.regplot, line_kws={'color':'green'}) g.map_upper(sns.regplot, line_kws={'color':'green'})
g.map_lower(sns.kdeplot) g.map_lower(sns.kdeplot)
g.map_diag(sns.kdeplot, lw=3) g.map_diag(sns.kdeplot, lw=3)
``` ```
......
Supports Markdown
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