"> 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",
"### Adding error bars\n",
"If your data is not completely perfect and has for some obscure reason some uncertainty associated with it, \n",
"plt.text(0.5, 0.5, 'middle of the plot', transform=plt.gca().transAxes, ha='center', va='center')\n",
"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",
"metadata": {},
"source": [
"By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),\n",
"however you can change that. For example to find the middle of the plot in the last example we use\n",
"axes coordinates, which are always (0, 0) in the lower left and (1, 1) in the upper right.\n",
"See the matplotlib [transformations tutorial](https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html)\n",
"for more detail.\n",
"\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",
"To prettify this plots, we first need to know what all the features are called:\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",
"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",
"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()`.\n",
"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.\n",
"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.\n",
"\n",
"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.\n",
"In that case we want to be more explicit about what sub-plot we want to add the artist to.\n",
"We can do this by switching from the \"procedural\" interface used above to the \"object-oriented\" interface.\n",
"The commands are very similar, we just have to do a little more setup.\n",
"For example, the equivalent of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])` is:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "19752271",
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure()\n",
"ax = fig.add_subplot()\n",
"ax.plot([1, 2, 3], [1.3, 4.2, 3.1])"
]
},
{
"cell_type": "markdown",
"id": "fe750f08",
"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",
"## 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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7f35488a",
"metadata": {},
"outputs": [],
"source": [
"plt.subplot(221)\n",
"plt.title(\"Upper left\")\n",
"plt.subplot(222)\n",
"plt.title(\"Upper right\")\n",
"plt.subplot(223)\n",
"plt.title(\"Lower left\")\n",
"plt.subplot(224)\n",
"plt.title(\"Lower right\")"
]
},
{
"cell_type": "markdown",
"id": "490dd65c",
"metadata": {},
"source": [
"For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the\n",
"code to figure out which of the subplots this specific `plt.title` command is affecting.\n",
"\n",
"The recommended way to this instead is:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b779ce08",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots(nrows=2, ncols=2)\n",
"axes[0, 0].set_title(\"Upper left\")\n",
"axes[0, 1].set_title(\"Upper right\")\n",
"axes[1, 0].set_title(\"Lower left\")\n",
"axes[1, 1].set_title(\"Lower right\")"
]
},
{
"cell_type": "markdown",
"id": "15f4138d",
"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",
"### 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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad25c7d6",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots(nrows=2, ncols=2)\n",
"axes[0, 0].set_title(\"Upper left\")\n",
"axes[0, 1].set_title(\"Upper right\")\n",
"axes[1, 0].set_title(\"Lower left\")\n",
"axes[1, 1].set_title(\"Lower right\")\n",
"fig.tight_layout()"
]
},
{
"cell_type": "markdown",
"id": "c37f8dbe",
"metadata": {},
"source": [
"Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.\n",
"If you want more explicit control, you can use `fig.subplots_adjust` (or `plt.subplots_adjust` to do this for the active figure).\n",
"For example, we can remove any whitespace between the plots using:"
"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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "abd57aac",
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(constrained_layout=True)\n",
"gs = fig.add_gridspec(3, 3)\n",
"f3_ax1 = fig.add_subplot(gs[0, :])\n",
"f3_ax1.set_title('gs[0, :]')\n",
"f3_ax2 = fig.add_subplot(gs[1, :-1])\n",
"f3_ax2.set_title('gs[1, :-1]')\n",
"f3_ax3 = fig.add_subplot(gs[1:, -1])\n",
"f3_ax3.set_title('gs[1:, -1]')\n",
"f3_ax4 = fig.add_subplot(gs[-1, 0])\n",
"f3_ax4.set_title('gs[-1, 0]')\n",
"f3_ax5 = fig.add_subplot(gs[-1, -2])\n",
"f3_ax5.set_title('gs[-1, -2]')"
]
},
{
"cell_type": "markdown",
"id": "dba57d95",
"metadata": {},
"source": [
"## Styling your plot\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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "777873ac",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots()\n",
"axes.plot([1, 2, 3], [2.3, 4.1, 0.8])\n",
"axes.set_xlabel('xlabel')\n",
"axes.set_ylabel('ylabel')\n",
"axes.set_title('title')"
]
},
{
"cell_type": "markdown",
"id": "a4702249",
"metadata": {},
"source": [
"You can also set any of these properties by calling `Axes.set` directly:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2330c244",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots()\n",
"axes.plot([1, 2, 3], [2.3, 4.1, 0.8])\n",
"axes.set(\n",
" xlabel='xlabel',\n",
" ylabel='ylabel',\n",
" title='title',\n",
")"
]
},
{
"cell_type": "markdown",
"id": "42c6eaa2",
"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",
"\n",
"You can edit the font of the text when setting the label:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f17bf9f6",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots()\n",
"axes.plot([1, 2, 3], [2.3, 4.1, 0.8])\n",
"axes.set_xlabel(\"xlabel\", color='red')\n",
"axes.set_ylabel(\"ylabel\", fontsize='larger')"
]
},
{
"cell_type": "markdown",
"id": "8ae4d1f4",
"metadata": {},
"source": [
"### 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",
"- The range shown on an axis can be set using `ax.set_xlim` (or `plt.xlim`)\n",
"- You can switch to a logarithmic (or other) axis using `ax.set_xscale('log')`\n",
"- The location of the ticks can be set using `ax.set_xticks` (or `plt.xticks`)\n",
"- The text shown for the ticks can be set using `ax.set_xticklabels` (or as a second argument to `plt.xticks`)\n",
"- The style of the ticks can be adjusted by looping through the ticks (obtained through `ax.get_xticks` or calling `plt.xticks` without arguments).\n",
"axes.set_xlabel(\"Progression through practical\")\n",
"axes.set_yticks((0, 0.5, 1))\n",
"axes.set_yticklabels(('0', '50%', '100%'))\n",
"fig.tight_layout()"
]
},
{
"cell_type": "markdown",
"id": "51567bd5",
"metadata": {},
"source": [
"## FAQ\n",
"### Why am I getting two images?\n",
"Any figure you produce in the notebook will be shown by default once you \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",
"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",
"\n",
"In this notebook we were using the `inline` backend, which is the default when running in a notebook.\n",
"While very robust, this backend has the disadvantage that it only produces static plots.\n",
"We could have had interactive plots if only we had changed backends to `nbagg`.\n",
"You can change backends in the IPython terminal/notebook using:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9606417d",
"metadata": {},
"outputs": [],
"source": [
"%matplotlib nbagg"
]
},
{
"cell_type": "markdown",
"id": "9247197f",
"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",
"\n",
"In python scripts, this will give you a syntax error and you should instead use:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9ef67e79",
"metadata": {},
"outputs": [],
"source": [
"import matplotlib\n",
"matplotlib.use(\"osx\")"
]
},
{
"cell_type": "markdown",
"id": "0ad7600b",
"metadata": {},
"source": [
"Usually, the default backend will be fine, so you will not have to set it. \n",
"Note that setting it explicitly will make your script less portable."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
%% Cell type:markdown id:551c06a5 tags:
# Plotting with python
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
Let's start with the basic imports:
%% Cell type:code id:16caed03 tags:
```
import matplotlib.pyplot as plt
import numpy as np
```
%% Cell type:markdown id:de78e9ca tags:
### Line plots
A basic lineplot can be made just by calling `plt.plot`:
%% Cell type:code id:a6b829fa tags:
```
plt.plot([1, 2, 3], [1.3, 4.2, 3.1])
```
%% Cell type:markdown id:e17e9bab tags:
To adjust how the line is plotted, check the documentation:
%% Cell type:code id:5d89403a tags:
```
plt.plot?
```
%% Cell type:markdown id:c91a5bd4 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)
> 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.
### 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:
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.
## 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:
```
fig = plt.figure()
ax = fig.add_subplot()
ax.plot([1, 2, 3], [1.3, 4.2, 3.1])
```
%% Cell type:markdown id:fe750f08 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.
## 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:7f35488a tags:
```
plt.subplot(221)
plt.title("Upper left")
plt.subplot(222)
plt.title("Upper right")
plt.subplot(223)
plt.title("Lower left")
plt.subplot(224)
plt.title("Lower right")
```
%% Cell type:markdown id:490dd65c tags:
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:
```
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:
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)
### 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:
```
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:
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:
fig.suptitle("group of plots, sharing x- and y-axes")
fig.subplots_adjust(wspace=0, hspace=0, top=0.9)
```
%% Cell type:markdown id:dd3db134 tags:
### Advanced grid configurations (GridSpec)
You can create more advanced grid layouts using [GridSpec](https://matplotlib.org/stable/tutorials/intermediate/gridspec.html).
An example taken from that website is:
%% Cell type:code id:abd57aac tags:
```
fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(3, 3)
f3_ax1 = fig.add_subplot(gs[0, :])
f3_ax1.set_title('gs[0, :]')
f3_ax2 = fig.add_subplot(gs[1, :-1])
f3_ax2.set_title('gs[1, :-1]')
f3_ax3 = fig.add_subplot(gs[1:, -1])
f3_ax3.set_title('gs[1:, -1]')
f3_ax4 = fig.add_subplot(gs[-1, 0])
f3_ax4.set_title('gs[-1, 0]')
f3_ax5 = fig.add_subplot(gs[-1, -2])
f3_ax5.set_title('gs[-1, -2]')
```
%% Cell type:markdown id:dba57d95 tags:
## Styling your plot
### Setting title and labels
You can edit a large number of plot properties by using the `Axes.set_*` interface.
We have already seen several examples of this above, but here is one more:
%% Cell type:code id:777873ac tags:
```
fig, axes = plt.subplots()
axes.plot([1, 2, 3], [2.3, 4.1, 0.8])
axes.set_xlabel('xlabel')
axes.set_ylabel('ylabel')
axes.set_title('title')
```
%% Cell type:markdown id:a4702249 tags:
You can also set any of these properties by calling `Axes.set` directly:
%% Cell type:code id:2330c244 tags:
```
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:
> 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:
%% Cell type:code id:f17bf9f6 tags:
```
fig, axes = plt.subplots()
axes.plot([1, 2, 3], [2.3, 4.1, 0.8])
axes.set_xlabel("xlabel", color='red')
axes.set_ylabel("ylabel", fontsize='larger')
```
%% Cell type:markdown id:8ae4d1f4 tags:
### Editing the x- and y-axis
We can change many of the properties of the x- and y-axis by using `set_` commands.
- The range shown on an axis can be set using `ax.set_xlim` (or `plt.xlim`)
- You can switch to a logarithmic (or other) axis using `ax.set_xscale('log')`
- The location of the ticks can be set using `ax.set_xticks` (or `plt.xticks`)
- The text shown for the ticks can be set using `ax.set_xticklabels` (or as a second argument to `plt.xticks`)
- The style of the ticks can be adjusted by looping through the ticks (obtained through `ax.get_xticks` or calling `plt.xticks` without arguments).
Any figure you produce in the notebook will be shown by default once you
### 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
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:
```
%matplotlib nbagg
```
%% Cell type:markdown id:9247197f 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:
```
import matplotlib
matplotlib.use("osx")
```
%% Cell type:markdown id:0ad7600b 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.
> 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) to see if they have what you want.
> 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.
### Adding error bars
### Adding error bars
If your data is not completely perfect and has for some obscure reason some uncertainty associated with it,
If your data is not completely perfect and has for some obscure reason some uncertainty associated with it,
plt.annotate("line crossing", (1, -1), (1, 1)) # adds both text and arrow
plt.text(0.5, 0.5, 'middle of the plot', transform=plt.gca().transAxes, ha='center', va='center')
plt.text(0.5, 0.5, 'middle of the plot', transform=plt.gca().transAxes)
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
```
```
By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),
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
however you can change that. For example to find the middle of the plot in the last example we use
...
@@ -171,10 +173,10 @@ To prettify this plots, we first need to know what all the features are called:
...
@@ -171,10 +173,10 @@ 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])`
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:
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()`.
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()`.
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.
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.
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.
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.
In that case we want to be more explicit about what sub-plot we want to add the artist to.
...
@@ -219,18 +221,14 @@ The returned `axes` object is in this case a 2x2 array of `Axes` objects, to whi
...
@@ -219,18 +221,14 @@ The returned `axes` object is in this case a 2x2 array of `Axes` objects, to whi
> 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)
> 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)
### Adjusting plot layout
### Adjusting plot layout
The default layout of sub-plots is usually good enough, however sometimes you will need some extra space to the plot to accomodate your large axes labels and ticks or you want to get rid of some of the whitespace.
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:
fig.set_suptitle("group of plots, where each row shares the x-axis and each column the y-axis")
fig.suptitle("group of plots, sharing x- and y-axes")
fig.subplots_adjust(width=0, height=0, top=0.9)
fig.subplots_adjust(wspace=0, hspace=0, top=0.9)
```
```
### Advanced grid configurations (GridSpec)
### Advanced grid configurations (GridSpec)
...
@@ -287,39 +285,39 @@ axes.set(
...
@@ -287,39 +285,39 @@ axes.set(
> 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.
> 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 either when setting the label or after the fact.
You can edit the font of the text when setting the label:
As an example, here are three ways to change the label colours:
```
```
fig, axes = plt.subplots()
fig, axes = plt.subplots()
axes.plot([1, 2, 3], [2.3, 4.1, 0.8])
axes.plot([1, 2, 3], [2.3, 4.1, 0.8])
axes.set_xlabel("xlabel", color='red') # set color when setting text label
axes.set_xlabel("xlabel", color='red')
label = axes.set_ylabel("ylabel") # keep track of the Text object returned by `set_?`
axes.set_ylabel("ylabel", fontsize='larger')
label.set_color('blue')
axes.set_title("title")
axes.get_title().set_color('green') # use `get_?` to get the Text object after the fact
```
```
### Editing the x- and y-axis
### Editing the x- and y-axis
We can change many of the properties of the x- and y-axis by using `set_` commands.
We can change many of the properties of the x- and y-axis by using `set_` commands.
- The range shown on an axis can be set using `ax.set_xlim` (or `plt.xlim`)
- The range shown on an axis can be set using `ax.set_xlim` (or `plt.xlim`)
- You can switch to a logarithmic (or other) axis using `ax.set_xscale('log')`
- You can switch to a logarithmic (or other) axis using `ax.set_xscale('log')`
- The location of the ticks can be set using `ax.set_xticks` (or `plt.xticks`)
- The location of the ticks can be set using `ax.set_xticks` (or `plt.xticks`)
- The text shown for the ticks can be set using `ax.set_xticklabels` (or as a second argument to `plt.xticks`)
- The text shown for the ticks can be set using `ax.set_xticklabels` (or as a second argument to `plt.xticks`)
- The style of the ticks can be adjusted by looping through the ticks (obtained through `ax.get_xticks` or calling `plt.xticks` without arguments).
- The style of the ticks can be adjusted by looping through the ticks (obtained through `ax.get_xticks` or calling `plt.xticks` without arguments).