"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.
> 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.
<aclass="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,
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:62d70058 tags:
%% Cell type:markdown id:finished-canon 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.
<aclass="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:
Based on this plot let's figure out 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:19752271 tags:
%% Cell type:code id:original-melissa tags:
```
```python
fig=plt.figure()
ax=fig.add_subplot()
ax.plot([1,2,3],[1.3,4.2,3.1])
```
%% Cell type:markdown id:fe750f08 tags:
%% Cell type:markdown id:handy-anniversary 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.
<aclass="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:
For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the
code to figure out which of the subplots this specific `plt.title` command is affecting.
The recommended way to this instead is:
%% Cell type:code id:b779ce08 tags:
%% Cell type:code id:elect-printer tags:
```
```python
fig,axes=plt.subplots(nrows=2,ncols=2)
axes[0,0].set_title("Upper left")
axes[0,1].set_title("Upper right")
axes[1,0].set_title("Lower left")
axes[1,1].set_title("Lower right")
```
%% Cell type:markdown id:15f4138d tags:
%% Cell type:markdown id:brief-auction tags:
Here we use `plt.subplots`, which creates both a new figure for us and a grid of sub-plots.
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.
> 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)
<aclass="anchor"id="layout"></a>
### Adjusting plot layout
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:
%% Cell type:code id:ad25c7d6 tags:
%% Cell type:code id:binding-tobacco tags:
```
```python
fig,axes=plt.subplots(nrows=2,ncols=2)
axes[0,0].set_title("Upper left")
axes[0,1].set_title("Upper right")
axes[1,0].set_title("Lower left")
axes[1,1].set_title("Lower right")
fig.tight_layout()
```
%% Cell type:markdown id:c37f8dbe tags:
%% Cell type:markdown id:canadian-africa tags:
Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.
If you want more explicit control, you can use `fig.subplots_adjust` (or `plt.subplots_adjust` to do this for the active figure).
For example, we can remove any whitespace between the plots using:
You can also set any of these properties by calling `Axes.set` directly:
%% Cell type:code id:2330c244 tags:
%% Cell type:code id:afraid-fields tags:
```
```python
fig,axes=plt.subplots()
axes.plot([1,2,3],[2.3,4.1,0.8])
axes.set(
xlabel='xlabel',
ylabel='ylabel',
title='title',
)
```
%% Cell type:markdown id:42c6eaa2 tags:
%% Cell type:markdown id:hired-journey tags:
> 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.
You can edit the font of the text when setting the label:
Any figure you produce in the notebook will be shown by default once you
Any figure you produce in the notebook will be shown by default once a cell successfully finishes (i.e., without error).
If the code in a notebook cell crashes after creating the figure, this figure will still be in memory.
It will be shown after another cell successfully finishes.
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.
<aclass="anchor"id="show"></a>
### I produced a plot in my python script, but it does not show up?
Add `plt.show()` to the end of your script (or save the figure to a file using `plt.savefig` or `fig.savefig`).
`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.
### Changing where the image appaers: backends
<aclass="anchor"id="backends"></a>
### Changing where the image appears: backends
Matplotlib works across a wide range of environments: Linux, Mac OS, Windows, in the browser, and more.
The exact detail of how to show you your plot will be different across all of these environments.
This procedure used to translate your `Figure`/`Axes` objects into an actual visualisation is called the backend.
In this notebook we were using the `inline` backend, which is the default when running in a notebook.
While very robust, this backend has the disadvantage that it only produces static plots.
We could have had interactive plots if only we had changed backends to `nbagg`.
You can change backends in the IPython terminal/notebook using:
%% Cell type:code id:9606417d tags:
%% Cell type:code id:directed-trouble tags:
```
```python
%matplotlibnbagg
```
%% Cell type:markdown id:9247197f tags:
%% Cell type:markdown id:indian-integrity tags:
> 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).
In python scripts, this will give you a syntax error and you should instead use:
%% Cell type:code id:9ef67e79 tags:
%% Cell type:code id:pregnant-raising tags:
```
```python
importmatplotlib
matplotlib.use("osx")
```
%% Cell type:markdown id:0ad7600b tags:
%% Cell type:markdown id:ceramic-liquid tags:
Usually, the default backend will be fine, so you will not have to set it.
Note that setting it explicitly will make your script less portable.
-[I produced a plot in my python script, but it does not show up](#show)
-[Changing where the image appears: backends](#backends)
<aclass="anchor"id="basic-plotting-commands"></a>
## Basic plotting commands
Let's start with the basic imports:
```
import matplotlib.pyplot as plt
import numpy as np
```
<aclass="anchor"id="line"></a>
### Line plots
A basic lineplot can be made just by calling `plt.plot`:
```
...
...
@@ -51,6 +73,7 @@ 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')
```
<aclass="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:
```
...
...
@@ -60,6 +83,7 @@ plt.scatter(x, y, x * 30, y)
plt.colorbar() # adds a colorbar
```
The third argument is the variable determining the size, while the fourth argument is the variable setting the color.
<aclass="anchor"id="histograms"></a>
### Histograms and bar plots
For a simple histogram you can do this:
```
...
...
@@ -87,6 +111,7 @@ plt.legend(loc='upper left')
> 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.
<aclass="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,
An area below a plot can be shaded using `plt.fill`
```
...
...
@@ -121,6 +147,7 @@ plt.plot(x, y, 'r')
plt.fill_between(x, yl, yu)
```
<aclass="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)
...
...
@@ -150,6 +177,7 @@ plt.grid('off')
```
> It is easier to produce informative brain images using nilearn or fsleyes
<aclass="anchor"id="annotations"></a>
### Adding lines, arrows, and text
Adding horizontal/vertical lines, arrows, and text:
```
...
...
@@ -165,6 +193,7 @@ axes coordinates, which are always (0, 0) in the lower left and (1, 1) in the up
See the matplotlib [transformations tutorial](https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html)
for more detail.
<aclass="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.
...
...
@@ -192,6 +221,8 @@ Note that here we explicitly create the figure and add a single sub-plot to the
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.
<aclass="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:
...
...
@@ -220,6 +251,7 @@ Here we use `plt.subplots`, which creates both a new figure for us and a grid of
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.
> 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)
<aclass="anchor"id="layout"></a>
### Adjusting plot layout
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:
```
...
...
@@ -243,6 +275,7 @@ fig.suptitle("group of plots, sharing x- and y-axes")
fig.subplots_adjust(wspace=0, hspace=0, top=0.9)
```
<aclass="anchor"id="grid-spec"></a>
### Advanced grid configurations (GridSpec)
You can create more advanced grid layouts using [GridSpec](https://matplotlib.org/stable/tutorials/intermediate/gridspec.html).