Commit bea989b4 authored by Michiel Cottaar's avatar Michiel Cottaar Committed by Michiel Cottaar
Browse files

added table of contents

parent 389147fd
......@@ -2,10 +2,10 @@
"cells": [
{
"cell_type": "markdown",
"id": "551c06a5",
"id": "ignored-think",
"metadata": {},
"source": [
"# Plotting with python\n",
"# Matplotlib tutorial\n",
"\n",
"The main plotting library in python is `matplotlib`. \n",
"It provides a simple interface to just explore the data, \n",
......@@ -20,6 +20,27 @@
"Just find one that looks like what you want to do and click on it to see (and copy) the code used to generate the plot.\n",
"\n",
"## Contents\n",
"- [Basic plotting commands](#basic-plotting-commands)\n",
" - [Line plots](#line)\n",
" - [Scatter plots](#scatter)\n",
" - [Histograms and bar plots](#histograms)\n",
" - [Adding error bars](#error)\n",
" - [Shading regions](#shade)\n",
" - [Displaying images](#image)\n",
" - [Adding lines, arrows, text](#annotations)\n",
"- [Using the object-oriented interface](#OO)\n",
"- [Multiple plots (i.e., subplots)](#subplots)\n",
" - [Adjusting plot layouts](#layout)\n",
" - [Advanced grid configurations (GridSpec)](#grid-spec)\n",
"- [Styling your plot](#styling)\n",
" - [Setting title and labels](#labels)\n",
" - [Editing the x- and y-axis](#axis)\n",
"- [FAQ](#faq)\n",
" - [Why am I getting two images?](#double-image)\n",
" - [I produced a plot in my python script, but it does not show up](#show)\n",
" - [Changing where the image appears: backends](#backends)\n",
"\n",
"<a class=\"anchor\" id=\"basic-plotting-commands\"></a>\n",
"## Basic plotting commands\n",
"Let's start with the basic imports:"
]
......@@ -27,7 +48,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "16caed03",
"id": "material-fundamentals",
"metadata": {},
"outputs": [],
"source": [
......@@ -37,9 +58,10 @@
},
{
"cell_type": "markdown",
"id": "de78e9ca",
"id": "dying-savings",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"line\"></a>\n",
"### Line plots\n",
"A basic lineplot can be made just by calling `plt.plot`:"
]
......@@ -47,7 +69,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "a6b829fa",
"id": "determined-melissa",
"metadata": {},
"outputs": [],
"source": [
......@@ -56,7 +78,7 @@
},
{
"cell_type": "markdown",
"id": "e17e9bab",
"id": "optional-bloom",
"metadata": {},
"source": [
"To adjust how the line is plotted, check the documentation:"
......@@ -65,7 +87,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "5d89403a",
"id": "electric-purpose",
"metadata": {},
"outputs": [],
"source": [
......@@ -74,7 +96,7 @@
},
{
"cell_type": "markdown",
"id": "c91a5bd4",
"id": "offshore-narrative",
"metadata": {},
"source": [
"As you can see there are a lot of options.\n",
......@@ -87,7 +109,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "84b58452",
"id": "younger-recall",
"metadata": {},
"outputs": [],
"source": [
......@@ -101,7 +123,7 @@
},
{
"cell_type": "markdown",
"id": "0d2e8301",
"id": "fewer-wednesday",
"metadata": {},
"source": [
"Because these keywords are so common, you can actually set one or more of them by passing in a string as the third argument."
......@@ -110,7 +132,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "10c2404c",
"id": "romance-payment",
"metadata": {},
"outputs": [],
"source": [
......@@ -123,9 +145,10 @@
},
{
"cell_type": "markdown",
"id": "1e340fc7",
"id": "democratic-setting",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"scatter\"></a>\n",
"### Scatter plots\n",
"The main extra feature of `plt.scatter` over `plt.plot` is that you can vary the color and size of the points based on some other variable array:"
]
......@@ -133,7 +156,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "7f3852a6",
"id": "homeless-opening",
"metadata": {},
"outputs": [],
"source": [
......@@ -145,10 +168,11 @@
},
{
"cell_type": "markdown",
"id": "dcb5d48c",
"id": "sitting-scheme",
"metadata": {},
"source": [
"The third argument is the variable determining the size, while the fourth argument is the variable setting the color.\n",
"<a class=\"anchor\" id=\"histograms\"></a>\n",
"### Histograms and bar plots\n",
"For a simple histogram you can do this:"
]
......@@ -156,7 +180,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "50770a55",
"id": "trained-mechanism",
"metadata": {},
"outputs": [],
"source": [
......@@ -166,7 +190,7 @@
},
{
"cell_type": "markdown",
"id": "17bda7f4",
"id": "convinced-framework",
"metadata": {},
"source": [
"where it also returns the number of elements in each bin, as `n`, and\n",
......@@ -183,7 +207,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "85dbb204",
"id": "convinced-cricket",
"metadata": {},
"outputs": [],
"source": [
......@@ -198,11 +222,12 @@
},
{
"cell_type": "markdown",
"id": "acbbe7b5",
"id": "historical-content",
"metadata": {},
"source": [
"> If you want more advanced distribution plots beyond a simple histogram, have a look at the seaborn [gallery](https://seaborn.pydata.org/examples/index.html) for (too?) many options.\n",
"\n",
"<a class=\"anchor\" id=\"error\"></a>\n",
"### Adding error bars\n",
"If your data is not completely perfect and has for some obscure reason some uncertainty associated with it, \n",
"you can plot these using `plt.error`:"
......@@ -211,7 +236,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "e749b87e",
"id": "broken-deviation",
"metadata": {},
"outputs": [],
"source": [
......@@ -224,9 +249,10 @@
},
{
"cell_type": "markdown",
"id": "33914264",
"id": "shared-afghanistan",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"shade\"></a>\n",
"### Shading regions\n",
"An area below a plot can be shaded using `plt.fill`"
]
......@@ -234,7 +260,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "df50543b",
"id": "changed-dressing",
"metadata": {},
"outputs": [],
"source": [
......@@ -244,7 +270,7 @@
},
{
"cell_type": "markdown",
"id": "068a8056",
"id": "infrared-chinese",
"metadata": {},
"source": [
"This can be nicely combined with a polar projection, to create 2D orientation distribution functions:"
......@@ -253,7 +279,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "3b75271e",
"id": "alternative-johnson",
"metadata": {},
"outputs": [],
"source": [
......@@ -264,7 +290,7 @@
},
{
"cell_type": "markdown",
"id": "fff9ddbe",
"id": "primary-momentum",
"metadata": {},
"source": [
"The area between two lines can be shaded using `fill_between`:"
......@@ -273,7 +299,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "2bf5186f",
"id": "naughty-colors",
"metadata": {},
"outputs": [],
"source": [
......@@ -287,9 +313,10 @@
},
{
"cell_type": "markdown",
"id": "de59cfd2",
"id": "acknowledged-illustration",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"image\"></a>\n",
"### Displaying images\n",
"The main command for displaying images is `plt.imshow` (use `plt.pcolor` for cases where you do not have a regular grid)"
]
......@@ -297,7 +324,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "c28e90a1",
"id": "protected-toolbox",
"metadata": {},
"outputs": [],
"source": [
......@@ -313,7 +340,7 @@
},
{
"cell_type": "markdown",
"id": "58546cf4",
"id": "short-turkey",
"metadata": {},
"source": [
"Note that matplotlib will use the **voxel data orientation**, and that\n",
......@@ -325,7 +352,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "a7004276",
"id": "vulnerable-vegetation",
"metadata": {},
"outputs": [],
"source": [
......@@ -338,10 +365,11 @@
},
{
"cell_type": "markdown",
"id": "1f36a7a9",
"id": "danish-sandwich",
"metadata": {},
"source": [
"> It is easier to produce informative brain images using nilearn or fsleyes\n",
"<a class=\"anchor\" id=\"annotations\"></a>\n",
"### Adding lines, arrows, and text\n",
"Adding horizontal/vertical lines, arrows, and text:"
]
......@@ -349,7 +377,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "f411a442",
"id": "checked-helping",
"metadata": {},
"outputs": [],
"source": [
......@@ -362,7 +390,7 @@
},
{
"cell_type": "markdown",
"id": "62d70058",
"id": "finished-canon",
"metadata": {},
"source": [
"By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),\n",
......@@ -371,6 +399,7 @@
"See the matplotlib [transformations tutorial](https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html)\n",
"for more detail.\n",
"\n",
"<a class=\"anchor\" id=\"OO\"></a>\n",
"## Using the object-oriented interface\n",
"In the examples above we simply added multiple lines/points/bars/images \n",
"(collectively called artists in matplotlib) to a single plot.\n",
......@@ -394,7 +423,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "19752271",
"id": "original-melissa",
"metadata": {},
"outputs": [],
"source": [
......@@ -405,13 +434,15 @@
},
{
"cell_type": "markdown",
"id": "fe750f08",
"id": "handy-anniversary",
"metadata": {},
"source": [
"Note that here we explicitly create the figure and add a single sub-plot to the figure.\n",
"We then call the `plot` function explicitly on this figure.\n",
"The \"Axes\" object has all of the same plotting command as we used above,\n",
"although the commands to adjust the properties of things like the title, x-axis, and y-axis are slighly different.\n",
"\n",
"<a class=\"anchor\" id=\"subplots\"></a>\n",
"## Multiple plots (i.e., subplots)\n",
"As stated one of the strengths of the object-oriented interface is that it is easier to work with multiple plots. \n",
"While we could do this in the procedural interface:"
......@@ -420,7 +451,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "7f35488a",
"id": "occupied-enforcement",
"metadata": {},
"outputs": [],
"source": [
......@@ -436,7 +467,7 @@
},
{
"cell_type": "markdown",
"id": "490dd65c",
"id": "encouraging-poultry",
"metadata": {},
"source": [
"For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the\n",
......@@ -448,7 +479,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "b779ce08",
"id": "elect-printer",
"metadata": {},
"outputs": [],
"source": [
......@@ -461,13 +492,14 @@
},
{
"cell_type": "markdown",
"id": "15f4138d",
"id": "brief-auction",
"metadata": {},
"source": [
"Here we use `plt.subplots`, which creates both a new figure for us and a grid of sub-plots. \n",
"The returned `axes` object is in this case a 2x2 array of `Axes` objects, to which we set the title using the normal numpy indexing.\n",
"\n",
"> Seaborn is great for creating grids of closely related plots. Before you spent a lot of time implementing your own have a look if seaborn already has what you want on their [gallery](https://seaborn.pydata.org/examples/index.html)\n",
"<a class=\"anchor\" id=\"layout\"></a>\n",
"### Adjusting plot layout\n",
"The default layout of sub-plots often leads to overlap between the labels/titles of the various subplots (as above) or to excessive amounts of whitespace in between. We can often fix this by just adding `fig.tight_layout` (or `plt.tight_layout`) after making the plot:"
]
......@@ -475,7 +507,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "ad25c7d6",
"id": "binding-tobacco",
"metadata": {},
"outputs": [],
"source": [
......@@ -489,7 +521,7 @@
},
{
"cell_type": "markdown",
"id": "c37f8dbe",
"id": "canadian-africa",
"metadata": {},
"source": [
"Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.\n",
......@@ -500,7 +532,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "081cb8b8",
"id": "hollow-metadata",
"metadata": {},
"outputs": [],
"source": [
......@@ -515,9 +547,10 @@
},
{
"cell_type": "markdown",
"id": "dd3db134",
"id": "willing-grade",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"grid-spec\"></a>\n",
"### Advanced grid configurations (GridSpec)\n",
"You can create more advanced grid layouts using [GridSpec](https://matplotlib.org/stable/tutorials/intermediate/gridspec.html).\n",
"An example taken from that website is:"
......@@ -526,7 +559,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "abd57aac",
"id": "loved-munich",
"metadata": {},
"outputs": [],
"source": [
......@@ -546,10 +579,12 @@
},
{
"cell_type": "markdown",
"id": "dba57d95",
"id": "invalid-roads",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"styling\"></a>\n",
"## Styling your plot\n",
"<a class=\"anchor\" id=\"labels\"></a>\n",
"### Setting title and labels\n",
"You can edit a large number of plot properties by using the `Axes.set_*` interface.\n",
"We have already seen several examples of this above, but here is one more:"
......@@ -558,7 +593,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "777873ac",
"id": "roman-nicaragua",
"metadata": {},
"outputs": [],
"source": [
......@@ -571,7 +606,7 @@
},
{
"cell_type": "markdown",
"id": "a4702249",
"id": "appropriate-affairs",
"metadata": {},
"source": [
"You can also set any of these properties by calling `Axes.set` directly:"
......@@ -580,7 +615,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "2330c244",
"id": "afraid-fields",
"metadata": {},
"outputs": [],
"source": [
......@@ -595,7 +630,7 @@
},
{
"cell_type": "markdown",
"id": "42c6eaa2",
"id": "hired-journey",
"metadata": {},
"source": [
"> To match the matlab API and save some typing the equivalent commands in the procedural interface do not have the `set_` preset. So, they are `plt.xlabel`, `plt.ylabel`, `plt.title`. This is also true for many of the `set_` commands we will see below.\n",
......@@ -606,7 +641,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "f17bf9f6",
"id": "legislative-parallel",
"metadata": {},
"outputs": [],
"source": [
......@@ -618,9 +653,10 @@
},
{
"cell_type": "markdown",
"id": "8ae4d1f4",
"id": "possible-sacramento",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"axis\"></a>\n",
"### Editing the x- and y-axis\n",
"We can change many of the properties of the x- and y-axis by using `set_` commands.\n",
"\n",
......@@ -636,7 +672,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "6ffd540c",
"id": "executed-space",
"metadata": {},
"outputs": [],
"source": [
......@@ -657,17 +693,25 @@
},
{
"cell_type": "markdown",
"id": "51567bd5",
"id": "administrative-acquisition",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"faq\"></a>\n",
"## FAQ\n",
"<a class=\"anchor\" id=\"double-image\"></a>\n",
"### Why am I getting two images?\n",
"Any figure you produce in the notebook will be shown by default once you \n",
"Any figure you produce in the notebook will be shown by default once a cell successfully finishes (i.e., without error).\n",
"If the code in a notebook cell crashes after creating the figure, this figure will still be in memory.\n",
"It will be shown after another cell successfully finishes.\n",
"You can remove this additional plot simply by rerunning the cell, after which you should only see the plot produced by the cell in question.\n",
"\n",
"<a class=\"anchor\" id=\"show\"></a>\n",
"### I produced a plot in my python script, but it does not show up?\n",
"Add `plt.show()` to the end of your script (or save the figure to a file using `plt.savefig` or `fig.savefig`).\n",
"`plt.show` will show the image to you and will block the script to allow you to take in and adjust the figure before saving or discarding it.\n",
"\n",
"### Changing where the image appaers: backends\n",
"<a class=\"anchor\" id=\"backends\"></a>\n",
"### Changing where the image appears: backends\n",
"Matplotlib works across a wide range of environments: Linux, Mac OS, Windows, in the browser, and more. \n",
"The exact detail of how to show you your plot will be different across all of these environments.\n",
"This procedure used to translate your `Figure`/`Axes` objects into an actual visualisation is called the backend.\n",
......@@ -681,7 +725,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "9606417d",
"id": "directed-trouble",
"metadata": {},
"outputs": [],
"source": [
......@@ -690,7 +734,7 @@
},
{
"cell_type": "markdown",
"id": "9247197f",
"id": "indian-integrity",
"metadata": {},
"source": [
"> If you are using Jupyterlab (new version of the jupyter notebook) the `nbagg` backend will not work. Instead you will have to install `ipympl` and then use the `widgets` backend to get an interactive backend (this also works in the old notebooks).\n",
......@@ -701,7 +745,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "9ef67e79",
"id": "pregnant-raising",
"metadata": {},
"outputs": [],
"source": [
......@@ -711,7 +755,7 @@
},
{
"cell_type": "markdown",
"id": "0ad7600b",
"id": "ceramic-liquid",
"metadata": {},
"source": [
"Usually, the default backend will be fine, so you will not have to set it. \n",
......@@ -719,7 +763,25 @@
]
}
],
"metadata": {},
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
%% Cell type:markdown id:551c06a5 tags:
%% Cell type:markdown id:ignored-think tags:
# Plotting with python
# Matplotlib tutorial
The main plotting library in python is `matplotlib`.
It provides a simple interface to just explore the data,
while also having a lot of flexibility to create publication-worthy plots.
In fact, the vast majority of python-produced plots in papers will be either produced
directly using matplotlib or by one of the many plotting libraries built on top of
matplotlib (such as [seaborn](https://seaborn.pydata.org/) or [nilearn](https://nilearn.github.io/)).
Like everything in python, there is a lot of help available online (just google it or ask your local pythonista).
A particularly useful resource for matplotlib is the [gallery](https://matplotlib.org/gallery/index.html).
Here you can find a wide range of plots.
Just find one that looks like what you want to do and click on it to see (and copy) the code used to generate the plot.
## Contents
- [Basic plotting commands](#basic-plotting-commands)
- [Line plots](#line)
- [Scatter plots](#scatter)
- [Histograms and bar plots](#histograms)
- [Adding error bars](#error)
- [Shading regions](#shade)
- [Displaying images](#image)
- [Adding lines, arrows, text](#annotations)
- [Using the object-oriented interface](#OO)
- [Multiple plots (i.e., subplots)](#subplots)
- [Adjusting plot layouts](#layout)
- [Advanced grid configurations (GridSpec)](#grid-spec)
- [Styling your plot](#styling)
- [Setting title and labels](#labels)
- [Editing the x- and y-axis](#axis)
- [FAQ](#faq)
- [Why am I getting two images?](#double-image)
- [I produced a plot in my python script, but it does not show up](#show)
- [Changing where the image appears: backends](#backends)
<a class="anchor" id="basic-plotting-commands"></a>
## Basic plotting commands
Let's start with the basic imports:
%% Cell type:code id:16caed03 tags:
%% Cell type:code id:material-fundamentals tags:
```
``` python
import matplotlib.pyplot as plt
import numpy as np
```
%% Cell type:markdown id:de78e9ca tags:
%% Cell type:markdown id:dying-savings tags:
<a class="anchor" id="line"></a>
### Line plots
A basic lineplot can be made just by calling `plt.plot`:
%% Cell type:code id:a6b829fa tags:
%% Cell type:code id:determined-melissa tags:
```
``` python
plt.plot([1, 2, 3], [1.3, 4.2, 3.1])
```
%% Cell type:markdown id:e17e9bab tags:
%% Cell type:markdown id:optional-bloom tags:
To adjust how the line is plotted, check the documentation:
%% Cell type:code id:5d89403a tags:
%% Cell type:code id:electric-purpose tags:
```
``` python
plt.plot?
```
%% Cell type:markdown id:c91a5bd4 tags: