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

Fix the link to the anatomy of a plot figure

parent bea989b4
......@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "markdown",
"id": "ignored-think",
"id": "christian-smart",
"metadata": {},
"source": [
"# Matplotlib tutorial\n",
......@@ -48,7 +48,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "material-fundamentals",
"id": "quick-postage",
"metadata": {},
"outputs": [],
"source": [
......@@ -58,7 +58,7 @@
},
{
"cell_type": "markdown",
"id": "dying-savings",
"id": "prescribed-writing",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"line\"></a>\n",
......@@ -69,7 +69,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "determined-melissa",
"id": "turkish-marsh",
"metadata": {},
"outputs": [],
"source": [
......@@ -78,7 +78,7 @@
},
{
"cell_type": "markdown",
"id": "optional-bloom",
"id": "compact-modeling",
"metadata": {},
"source": [
"To adjust how the line is plotted, check the documentation:"
......@@ -87,7 +87,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "electric-purpose",
"id": "distinct-coordinate",
"metadata": {},
"outputs": [],
"source": [
......@@ -96,7 +96,7 @@
},
{
"cell_type": "markdown",
"id": "offshore-narrative",
"id": "green-dutch",
"metadata": {},
"source": [
"As you can see there are a lot of options.\n",
......@@ -109,7 +109,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "younger-recall",
"id": "adjacent-satellite",
"metadata": {},
"outputs": [],
"source": [
......@@ -123,7 +123,7 @@
},
{
"cell_type": "markdown",
"id": "fewer-wednesday",
"id": "external-meaning",
"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."
......@@ -132,7 +132,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "romance-payment",
"id": "simple-korean",
"metadata": {},
"outputs": [],
"source": [
......@@ -145,7 +145,7 @@
},
{
"cell_type": "markdown",
"id": "democratic-setting",
"id": "pediatric-sullivan",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"scatter\"></a>\n",
......@@ -156,7 +156,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "homeless-opening",
"id": "bright-preparation",
"metadata": {},
"outputs": [],
"source": [
......@@ -168,7 +168,7 @@
},
{
"cell_type": "markdown",
"id": "sitting-scheme",
"id": "asian-mailing",
"metadata": {},
"source": [
"The third argument is the variable determining the size, while the fourth argument is the variable setting the color.\n",
......@@ -180,7 +180,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "trained-mechanism",
"id": "massive-relative",
"metadata": {},
"outputs": [],
"source": [
......@@ -190,7 +190,7 @@
},
{
"cell_type": "markdown",
"id": "convinced-framework",
"id": "positive-insight",
"metadata": {},
"source": [
"where it also returns the number of elements in each bin, as `n`, and\n",
......@@ -207,7 +207,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "convinced-cricket",
"id": "intensive-taste",
"metadata": {},
"outputs": [],
"source": [
......@@ -222,7 +222,7 @@
},
{
"cell_type": "markdown",
"id": "historical-content",
"id": "boolean-metropolitan",
"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",
......@@ -236,7 +236,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "broken-deviation",
"id": "basic-cambridge",
"metadata": {},
"outputs": [],
"source": [
......@@ -249,7 +249,7 @@
},
{
"cell_type": "markdown",
"id": "shared-afghanistan",
"id": "twelve-assist",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"shade\"></a>\n",
......@@ -260,7 +260,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "changed-dressing",
"id": "stuck-teaching",
"metadata": {},
"outputs": [],
"source": [
......@@ -270,7 +270,7 @@
},
{
"cell_type": "markdown",
"id": "infrared-chinese",
"id": "metric-chemical",
"metadata": {},
"source": [
"This can be nicely combined with a polar projection, to create 2D orientation distribution functions:"
......@@ -279,7 +279,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "alternative-johnson",
"id": "democratic-israel",
"metadata": {},
"outputs": [],
"source": [
......@@ -290,7 +290,7 @@
},
{
"cell_type": "markdown",
"id": "primary-momentum",
"id": "connected-consideration",
"metadata": {},
"source": [
"The area between two lines can be shaded using `fill_between`:"
......@@ -299,7 +299,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "naughty-colors",
"id": "engaged-lottery",
"metadata": {},
"outputs": [],
"source": [
......@@ -313,7 +313,7 @@
},
{
"cell_type": "markdown",
"id": "acknowledged-illustration",
"id": "paperback-stylus",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"image\"></a>\n",
......@@ -324,7 +324,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "protected-toolbox",
"id": "acoustic-kitchen",
"metadata": {},
"outputs": [],
"source": [
......@@ -340,7 +340,7 @@
},
{
"cell_type": "markdown",
"id": "short-turkey",
"id": "frank-master",
"metadata": {},
"source": [
"Note that matplotlib will use the **voxel data orientation**, and that\n",
......@@ -352,7 +352,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "vulnerable-vegetation",
"id": "initial-passing",
"metadata": {},
"outputs": [],
"source": [
......@@ -365,7 +365,7 @@
},
{
"cell_type": "markdown",
"id": "danish-sandwich",
"id": "specialized-maintenance",
"metadata": {},
"source": [
"> It is easier to produce informative brain images using nilearn or fsleyes\n",
......@@ -377,7 +377,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "checked-helping",
"id": "weighted-publicity",
"metadata": {},
"outputs": [],
"source": [
......@@ -390,7 +390,7 @@
},
{
"cell_type": "markdown",
"id": "finished-canon",
"id": "manual-bacon",
"metadata": {},
"source": [
"By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),\n",
......@@ -404,8 +404,10 @@
"In the examples above we simply added multiple lines/points/bars/images \n",
"(collectively called artists in matplotlib) to a single plot.\n",
"To prettify this plots, we first need to know what all the features are called:\n",
"[[https://matplotlib.org/stable/_images/anatomy.png]]\n",
"Based on this plot let's figure out what our first command of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])`\n",
"\n",
"![anatomy of a plot](https://matplotlib.org/stable/_images/anatomy.png)\n",
"\n",
"Using the terms in this plot let's see what our first command of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])`\n",
"actually does:\n",
"\n",
"1. First it creates a figure and makes this the active figure. Being the active figure means that any subsequent commands will affect figure. You can find the active figure at any point by calling `plt.gcf()`.\n",
......@@ -423,7 +425,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "original-melissa",
"id": "earned-anaheim",
"metadata": {},
"outputs": [],
"source": [
......@@ -434,7 +436,7 @@
},
{
"cell_type": "markdown",
"id": "handy-anniversary",
"id": "valued-hungary",
"metadata": {},
"source": [
"Note that here we explicitly create the figure and add a single sub-plot to the figure.\n",
......@@ -451,7 +453,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "occupied-enforcement",
"id": "intensive-bruce",
"metadata": {},
"outputs": [],
"source": [
......@@ -467,7 +469,7 @@
},
{
"cell_type": "markdown",
"id": "encouraging-poultry",
"id": "upset-stanley",
"metadata": {},
"source": [
"For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the\n",
......@@ -479,7 +481,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "elect-printer",
"id": "frank-treatment",
"metadata": {},
"outputs": [],
"source": [
......@@ -492,7 +494,7 @@
},
{
"cell_type": "markdown",
"id": "brief-auction",
"id": "occupational-astronomy",
"metadata": {},
"source": [
"Here we use `plt.subplots`, which creates both a new figure for us and a grid of sub-plots. \n",
......@@ -507,7 +509,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "binding-tobacco",
"id": "joint-chick",
"metadata": {},
"outputs": [],
"source": [
......@@ -521,7 +523,7 @@
},
{
"cell_type": "markdown",
"id": "canadian-africa",
"id": "illegal-spanish",
"metadata": {},
"source": [
"Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.\n",
......@@ -532,7 +534,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "hollow-metadata",
"id": "accomplished-watershed",
"metadata": {},
"outputs": [],
"source": [
......@@ -547,7 +549,7 @@
},
{
"cell_type": "markdown",
"id": "willing-grade",
"id": "standing-course",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"grid-spec\"></a>\n",
......@@ -559,7 +561,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "loved-munich",
"id": "silent-voluntary",
"metadata": {},
"outputs": [],
"source": [
......@@ -579,7 +581,7 @@
},
{
"cell_type": "markdown",
"id": "invalid-roads",
"id": "roman-discharge",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"styling\"></a>\n",
......@@ -593,7 +595,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "roman-nicaragua",
"id": "english-yahoo",
"metadata": {},
"outputs": [],
"source": [
......@@ -606,7 +608,7 @@
},
{
"cell_type": "markdown",
"id": "appropriate-affairs",
"id": "constant-evolution",
"metadata": {},
"source": [
"You can also set any of these properties by calling `Axes.set` directly:"
......@@ -615,7 +617,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "afraid-fields",
"id": "suspended-biography",
"metadata": {},
"outputs": [],
"source": [
......@@ -630,7 +632,7 @@
},
{
"cell_type": "markdown",
"id": "hired-journey",
"id": "annual-hundred",
"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",
......@@ -641,7 +643,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "legislative-parallel",
"id": "trained-mouse",
"metadata": {},
"outputs": [],
"source": [
......@@ -653,7 +655,7 @@
},
{
"cell_type": "markdown",
"id": "possible-sacramento",
"id": "elementary-mentor",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"axis\"></a>\n",
......@@ -672,7 +674,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "executed-space",
"id": "capital-surgeon",
"metadata": {},
"outputs": [],
"source": [
......@@ -693,7 +695,7 @@
},
{
"cell_type": "markdown",
"id": "administrative-acquisition",
"id": "discrete-hartford",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"faq\"></a>\n",
......@@ -725,7 +727,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "directed-trouble",
"id": "fifty-relaxation",
"metadata": {},
"outputs": [],
"source": [
......@@ -734,7 +736,7 @@
},
{
"cell_type": "markdown",
"id": "indian-integrity",
"id": "fifty-sunglasses",
"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",
......@@ -745,7 +747,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "pregnant-raising",
"id": "underlying-dealer",
"metadata": {},
"outputs": [],
"source": [
......@@ -755,7 +757,7 @@
},
{
"cell_type": "markdown",
"id": "ceramic-liquid",
"id": "general-subscriber",
"metadata": {},
"source": [
"Usually, the default backend will be fine, so you will not have to set it. \n",
......
%% Cell type:markdown id:ignored-think tags:
%% Cell type:markdown id:christian-smart tags:
# 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:material-fundamentals tags:
%% Cell type:code id:quick-postage tags:
``` python
import matplotlib.pyplot as plt
import numpy as np
```
%% Cell type:markdown id:dying-savings tags:
%% Cell type:markdown id:prescribed-writing tags:
<a class="anchor" id="line"></a>
### Line plots
A basic lineplot can be made just by calling `plt.plot`:
%% Cell type:code id:determined-melissa tags:
%% Cell type:code id:turkish-marsh tags:
``` python
plt.plot([1, 2, 3], [1.3, 4.2, 3.1])
```
%% Cell type:markdown id:optional-bloom tags:
%% Cell type:markdown id:compact-modeling tags:
To adjust how the line is plotted, check the documentation:
%% Cell type:code id:electric-purpose tags:
%% Cell type:code id:distinct-coordinate tags:
``` python
plt.plot?
```
%% Cell type:markdown id:offshore-narrative tags:
%% Cell type:markdown id:green-dutch tags:
As you can see there are a lot of options.
The ones you will probably use most often are:
- `linestyle`: how the line is plotted (set to '' to omit the line)
- `marker`: how the points are plotted (these are not plotted by default)
- `color`: what color to use (defaults to cycling through a set of 7 colors)
%% Cell type:code id:younger-recall tags:
%% Cell type:code id:adjacent-satellite tags:
``` python
theta = np.linspace(0, 2 * np.pi, 101)
plt.plot(np.sin(theta), np.cos(theta))
plt.plot([-0.3, 0.3], [0.3, 0.3], marker='o', linestyle='', markersize=20)
plt.plot(0, -0.1, marker='s', color='black')
x = np.linspace(-0.5, 0.5, 5)
plt.plot(x, x ** 2 - 0.5, linestyle='--', marker='+', color='red')
```
%% Cell type:markdown id:fewer-wednesday tags:
%% Cell type:markdown id:external-meaning tags:
Because these keywords are so common, you can actually set one or more of them by passing in a string as the third argument.
%% Cell type:code id:romance-payment tags:
%% Cell type:code id:simple-korean tags:
``` python
x = np.linspace(0, 1, 11)
plt.plot(x, x)
plt.plot(x, x ** 2, '--') # sets the linestyle to dashed
plt.plot(x, x ** 3, 's') # sets the marker to square (and turns off the line)
plt.plot(x, x ** 4, '^y:') # sets the marker to triangles (i.e., '^'), linestyle to dotted (i.e., ':'), and the color to yellow (i.e., 'y')
```
%% Cell type:markdown id:democratic-setting tags:
%% Cell type:markdown id:pediatric-sullivan tags:
<a class="anchor" id="scatter"></a>
### Scatter plots
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:
%% Cell type:code id:homeless-opening tags:
%% Cell type:code id:bright-preparation tags:
``` python
x = np.random.rand(30)
y = np.random.rand(30)
plt.scatter(x, y, x * 30, y)
plt.colorbar() # adds a colorbar
```
%% Cell type:markdown id:sitting-scheme tags:
%% Cell type:markdown id:asian-mailing tags:
The third argument is the variable determining the size, while the fourth argument is the variable setting the color.
<a class="anchor" id="histograms"></a>
### Histograms and bar plots
For a simple histogram you can do this:
%% Cell type:code id:trained-mechanism tags:
%% Cell type:code id:massive-relative tags:
``` python
r = np.random.rand(1000)
n,bins,_ = plt.hist((r-0.5)**2, bins=30)
```
%% Cell type:markdown id:convinced-framework tags:
%% Cell type:markdown id:positive-insight tags:
where it also returns the number of elements in each bin, as `n`, and
the bin centres, as `bins`.
> The `_` in the third part on the left
> hand side is a shorthand for just throwing away the corresponding part
> of the return structure.
There is also a call for doing bar plots:
%% Cell type:code id:convinced-cricket tags:
%% Cell type:code id:intensive-taste tags:
``` python
samp1 = r[0:10]
samp2 = r[10:20]
bwidth = 0.3
xcoord = np.arange(10)
plt.bar(xcoord-bwidth, samp1, width=bwidth, color='red', label='Sample 1')
plt.bar(xcoord, samp2, width=bwidth, color='blue', label='Sample 2')
plt.legend(loc='upper left')
```
%% Cell type:markdown id:historical-content tags:
%% Cell type:markdown id:boolean-metropolitan tags:
> 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.
<a class="anchor" id="error"></a>
### Adding error bars
If your data is not completely perfect and has for some obscure reason some uncertainty associated with it,
you can plot these using `plt.error`:
%% Cell type:code id:broken-deviation tags:
%% Cell type:code id:basic-cambridge tags:
``` python
x = np.arange(5)
y1 = [0.3, 0.5, 0.7, 0.1, 0.3]
yerr = [0.12, 0.28, 0.1, 0.25, 0.6]
xerr = 0.3
plt.errorbar(x, y1, yerr, xerr, marker='s', linestyle='')
```
%% Cell type:markdown id:shared-afghanistan tags:
%% Cell type:markdown id:twelve-assist tags:
<a class="anchor" id="shade"></a>
### Shading regions
An area below a plot can be shaded using `plt.fill`
%% Cell type:code id:changed-dressing tags:
%% Cell type:code id:stuck-teaching tags:
``` python
x = np.linspace(0, 2, 100)
plt.fill(x, np.sin(x * np.pi))
```
%% Cell type:markdown id:infrared-chinese tags:
%% Cell type:markdown id:metric-chemical tags:
This can be nicely combined with a polar projection, to create 2D orientation distribution functions:
%% Cell type:code id:alternative-johnson tags:
%% Cell type:code id:democratic-israel tags:
``` python
plt.subplot(projection='polar')
theta = np.linspace(0, 2 * np.pi, 100)
plt.fill(theta, np.exp(-2 * np.cos(theta) ** 2))
```
%% Cell type:markdown id:primary-momentum tags:
%% Cell type:markdown id:connected-consideration tags:
The area between two lines can be shaded using `fill_between`:
%% Cell type:code id:naughty-colors tags:
%% Cell type:code id:engaged-lottery tags:
``` python
x = np.linspace(0, 10, 1000)
y = 5 * np.sin(5 * x) + x - 0.1 * x ** 2
yl = x - 0.1 * x ** 2 - 5
yu = yl + 10
plt.plot(x, y, 'r')
plt.fill_between(x, yl, yu)
```
%% Cell type:markdown id:acknowledged-illustration tags:
%% Cell type:markdown id:paperback-stylus tags:
<a class="anchor" id="image"></a>
### Displaying images
The main command for displaying images is `plt.imshow` (use `plt.pcolor` for cases where you do not have a regular grid)
%% Cell type:code id:protected-toolbox tags:
%% Cell type:code id:acoustic-kitchen tags:
``` python
import nibabel as nib
import os.path as op
nim = nib.load(op.expandvars('${FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'), mmap=False)
imdat = nim.get_data().astype(float)
imslc = imdat[:,:,70]
plt.imshow(imslc, cmap=plt.cm.gray)
plt.colorbar()
plt.grid('off')
```
%% Cell type:markdown id:short-turkey tags:
%% Cell type:markdown id:frank-master tags:
Note that matplotlib will use the **voxel data orientation**, and that
configuring the plot orientation is **your responsibility**. To rotate a
slice, simply transpose the data (`.T`). To invert the data along along an
axis, you don't need to modify the data - simply swap the axis limits around:
%% Cell type:code id:vulnerable-vegetation tags:
%% Cell type:code id:initial-passing tags:
``` python
plt.imshow(imslc.T, cmap=plt.cm.gray)
plt.xlim(reversed(plt.xlim()))
plt.ylim(reversed(plt.ylim()))
plt.colorbar()
plt.grid('off')
```
%% Cell type:markdown id:danish-sandwich tags:
%% Cell type:markdown id:specialized-maintenance tags:
> It is easier to produce informative brain images using nilearn or fsleyes
<a class="anchor" id="annotations"></a>
### Adding lines, arrows, and text
Adding horizontal/vertical lines, arrows, and text:
%% Cell type:code id:checked-helping tags:
%% Cell type:code id:weighted-publicity tags:
``` python
plt.axhline(-1) # horizontal line
plt.axvline(1) # vertical line
plt.arrow(0.2, -0.2, 0.2, -0.8, length_includes_head=True, width=0.01)
plt.text(0.5, 0.5, 'middle of the plot', transform=plt.gca().transAxes, ha='center', va='center')
plt.annotate("line crossing", (1, -1), (0.8, -0.8), arrowprops={}) # adds both text and arrow; need to set the arrowprops keyword for the arrow to be plotted
```
%% Cell type:markdown id:finished-canon tags:
%% Cell type:markdown id:manual-bacon tags:
By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),
however you can change that. For example to find the middle of the plot in the last example we use
axes coordinates, which are always (0, 0) in the lower left and (1, 1) in the upper right.
See the matplotlib [transformations tutorial](https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html)
for more detail.
<a class="anchor" id="OO"></a>
## Using the object-oriented interface
In the examples above we simply added multiple lines/points/bars/images
(collectively called artists in matplotlib) to a single plot.
To prettify this plots, we first need to know what all the features are called:
[[https://matplotlib.org/stable/_images/anatomy.png]]
Based on this plot let's figure out what our first command of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])`
![anatomy of a plot](https://matplotlib.org/stable/_images/anatomy.png)
Using the terms in this plot let's see what our first command of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])`
actually does:
1. First it creates a figure and makes this the active figure. Being the active figure means that any subsequent commands will affect figure. You can find the active figure at any point by calling `plt.gcf()`.
2. Then it creates an Axes or Subplot in the figure and makes this the active axes. Any subsequent commands will reuse this active axes. You can find the active axes at any point by calling `plt.gca()`.
3. Finally it creates a Line2D artist containing the x-coordinates `[1, 2, 3]` and `[1.3, 4.2, 3.1]` ands adds this to the active axes.
4. At some later time, when actually creating the plot, matplotlib will also automatically determine for you a default range for the x-axis and y-axis and where the ticks should be.
This concept of an "active" figure and "active" axes can be very helpful with a single plot, it can quickly get very confusing when you have multiple sub-plots within a figure or even multiple figures.
In that case we want to be more explicit about what sub-plot we want to add the artist to.
We can do this by switching from the "procedural" interface used above to the "object-oriented" interface.
The commands are very similar, we just have to do a little more setup.
For example, the equivalent of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])` is:
%% Cell type:code id:original-melissa tags:
%% Cell type:code id:earned-anaheim tags:
``` python
fig = plt.figure()
ax = fig.add_subplot()
ax.plot([1, 2, 3], [1.3, 4.2, 3.1])
```
%% Cell type:markdown id:handy-anniversary tags:
%% Cell type:markdown id:valued-hungary tags:
Note that here we explicitly create the figure and add a single sub-plot to the figure.
We then call the `plot` function explicitly on this figure.
The "Axes" object has all of the same plotting command as we used above,
although the commands to adjust the properties of things like the title, x-axis, and y-axis are slighly different.
<a class="anchor" id="subplots"></a>
## Multiple plots (i.e., subplots)
As stated one of the strengths of the object-oriented interface is that it is easier to work with multiple plots.
While we could do this in the procedural interface:
%% Cell type:code id:occupied-enforcement tags:
%% Cell type:code id:intensive-bruce tags:
``` python
plt.subplot(221)
plt.title("Upper left")
plt.subplot(222)