From acd5e3b8287fdf8d2497e40429373d7966627227 Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Mon, 26 Apr 2021 11:44:28 +0100 Subject: [PATCH 1/9] more detailed/advanced matplotlib practical --- applications/plotting/matplotlib.md | 351 ++++++++++++++++++++++++++++ 1 file changed, 351 insertions(+) create mode 100644 applications/plotting/matplotlib.md diff --git a/applications/plotting/matplotlib.md b/applications/plotting/matplotlib.md new file mode 100644 index 0000000..a2f62e9 --- /dev/null +++ b/applications/plotting/matplotlib.md @@ -0,0 +1,351 @@ +# 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: +``` +import matplotlib.pyplot as plt +import numpy as np +``` +### Line plots +A basic lineplot can be made just by calling `plt.plot`: +``` +plt.plot([1, 2, 3], [1.3, 4.2, 3.1]) +``` + +To adjust how the line is plotted, check the documentation: +``` +plt.plot? +``` + +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 None 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) +``` +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=None, size=10) +plt.plot(0, 0.1, marker='s', color='black') +plt.plot(0.5 * x, -0.5 * x ** 2 - 0.5, linestyle='--', marker='+', color='yellow') +``` +Because these keywords are so common, you can actually set them directly by passing in a string as the third argument. +``` +x = np.linspace(0, 1, 11) +plt.plot(x, x) +plt.plot(x, x, '--') # sets the linestyle to dashed +plt.plot(x, x, 's') # sets the marker to square (and turns off the line) +plt.plot(x, x, 'y:') # sets the linestyle to dotted (i.e., ':') and the color to yellow (i.e., 'y') +``` +Note in the last line that if you want to define both the color and the marker/linestyle you need to put the color identifier first. +### 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: +``` +x = np.random.rand(30) +y = np.random.rand(30) +plt.scatter(x, y, x, y) +plt.colorbar() # adds a colorbar +``` +The third argument is the variable determining the color, while the fourth argument is the variable setting the size. +### Histograms and bar plots +For a simple histogram you can do this: +``` +r = np.random.rand(1000) +n,bins,_ = plt.hist((r-0.5)**2, bins=30) +``` +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: +``` +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') +``` + +> 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. + +### 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`: +``` +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.error(x, y1, yerr, xerr, marker='s') +``` +### Shading regions +An area below a plot can be shaded using `plt.fill` +``` +x = np.linspace(0, 2, 100) +plt.fill(x, np.sin(x * np.pi)) +``` + +This can be nicely combined with a polar projection, to create nice polar plots: +``` +plt.subplot(project='polar') +theta = np.linspace(0, 2 * np.pi, 100) +plt.fill(theta, np.exp(-2 * np.cos(theta) ** 2)) +``` + +The area between two lines can be shaded using `fill_between`: +``` +x = np.linspace(0, 10, 100) +y = 5 * np.sin(x) + x - 0.1 * x ** 2 +yl = x - 0.1 * x ** 2 - 2.5 +yu = yl + 5 +plt.plot(x, y, 'r') +plt.fill_between(x, yl, yu) +``` + +### Displaying images +The main command for displaying images is `plt.imshow` (use `plt.pcolor` for cases where you do not have a regular grid) + +``` +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') +``` + +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: + + +``` +plt.imshow(imslc.T, cmap=plt.cm.gray) +plt.xlim(reversed(plt.xlim())) +plt.ylim(reversed(plt.ylim())) +plt.colorbar() +plt.grid('off') +``` +### Adding lines, arrows, and text +Adding horizontal/vertical lines, arrows, and text: +``` +plt.axhline(-1) # horizontal line +plt.axvline(1) # vertical line +plt.arrow(0.2, -0.2, 0.2, -0.8, length_includes_head=True) +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) +``` +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: +[[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])` +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: +``` +fig = plt.figure() +ax = fig.add_subplot() +ax.plot([1, 2, 3], [1.3, 4.2, 3.1]) +``` +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: +``` +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") +``` +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: +``` +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") +``` +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 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. +``` +np.random.seed(1) +fig, axes = plt.subplots(nrows=2, ncols=2) +for ax in axes.flat: + ax.scatter(np.random.randn(10), np.random.randn(10)) + ax.set( + title='long multi-\nline title', + xlabel='x-label', + ylabel='y-label', + ) +#fig.tight_layout() +``` +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: +``` +np.random.seed(1) +fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True) +for ax in axes.flat: + offset = np.random.rand(2) + ax.scatter(np.random.randn(10) + offset[0], np.random.randn(10) + offset[1]) +fig.set_suptitle("group of plots, where each row shares the x-axis and each column the y-axis") +fig.subplots_adjust(width=0, height=0, top=0.9) +``` + +### 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: +``` +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]') +``` + +## 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: +``` +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') +``` +You can also set any of these properties by calling `Axes.set` directly: +``` +fig, axes = plt.subplots() +axes.plot([1, 2, 3], [2.3, 4.1, 0.8]) +axes.set( + xlabel='xlabel', + ylabel='ylabel', + title='title', +) +``` + +> 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. +As an example, here are three ways to change the label colours: +``` +fig, axes = plt.subplots() +axes.plot([1, 2, 3], [2.3, 4.1, 0.8]) +axes.set_xlabel("xlabel", color='red') # set color when setting text label +label = axes.set_ylabel("ylabel") # keep track of the Text object returned by `set_?` +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 +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). + +For example: + +``` +fig, axes = plt.subplots() +axes.error([0, 1, 2], [0.8, 0.4, -0.2], 0.1, linestyle='0', marker='s') +axes.set_xticks((0, 1, 2)) +axes.set_xticklabels(('start', 'middle', 'end')) +for tick in axes.get_ticks(): + tick.set_rotation(45) +axes.set_xlabel("Progression through practical") +axes.set_yticks((0, 0.5, 1)) +axes.set_yticklabels(('0', '50%', '100%')) +``` +## FAQ +### Why am I getting two images? +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: +``` +%matplotlib nbagg +``` +> 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: +``` +import matplotlib +matplotlib.use("osx") +``` +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. \ No newline at end of file -- GitLab From 8d802184288f4ec1ea0bab299d3ec8037dd6f8a1 Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Mon, 26 Apr 2021 11:46:07 +0100 Subject: [PATCH 2/9] Refer to plotting practicals --- getting_started/06_plotting.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/getting_started/06_plotting.md b/getting_started/06_plotting.md index 95f5231..ed1e58e 100644 --- a/getting_started/06_plotting.md +++ b/getting_started/06_plotting.md @@ -225,3 +225,6 @@ example code from the docs). ``` # Make up some data and do the funky plot ``` + + +If you want more plotting goodneess, have a look at the various tutorials available in the `applications/plottings` folder. \ No newline at end of file -- GitLab From 389147fdf7863c96e1d8276e7ffd77e63725a84e Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Mon, 26 Apr 2021 14:48:02 +0100 Subject: [PATCH 3/9] fixed many bugs in practical --- applications/plotting/matplotlib.ipynb | 725 +++++++++++++++++++++++++ applications/plotting/matplotlib.md | 106 ++-- 2 files changed, 777 insertions(+), 54 deletions(-) create mode 100644 applications/plotting/matplotlib.ipynb diff --git a/applications/plotting/matplotlib.ipynb b/applications/plotting/matplotlib.ipynb new file mode 100644 index 0000000..20e6d5c --- /dev/null +++ b/applications/plotting/matplotlib.ipynb @@ -0,0 +1,725 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "551c06a5", + "metadata": {}, + "source": [ + "# Plotting with python\n", + "\n", + "The main plotting library in python is `matplotlib`. \n", + "It provides a simple interface to just explore the data, \n", + "while also having a lot of flexibility to create publication-worthy plots.\n", + "In fact, the vast majority of python-produced plots in papers will be either produced\n", + "directly using matplotlib or by one of the many plotting libraries built on top of\n", + "matplotlib (such as [seaborn](https://seaborn.pydata.org/) or [nilearn](https://nilearn.github.io/)).\n", + "\n", + "Like everything in python, there is a lot of help available online (just google it or ask your local pythonista).\n", + "A particularly useful resource for matplotlib is the [gallery](https://matplotlib.org/gallery/index.html).\n", + "Here you can find a wide range of plots. \n", + "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\n", + "Let's start with the basic imports:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16caed03", + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np" + ] + }, + { + "cell_type": "markdown", + "id": "de78e9ca", + "metadata": {}, + "source": [ + "### Line plots\n", + "A basic lineplot can be made just by calling `plt.plot`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a6b829fa", + "metadata": {}, + "outputs": [], + "source": [ + "plt.plot([1, 2, 3], [1.3, 4.2, 3.1])" + ] + }, + { + "cell_type": "markdown", + "id": "e17e9bab", + "metadata": {}, + "source": [ + "To adjust how the line is plotted, check the documentation:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5d89403a", + "metadata": {}, + "outputs": [], + "source": [ + "plt.plot?" + ] + }, + { + "cell_type": "markdown", + "id": "c91a5bd4", + "metadata": {}, + "source": [ + "As you can see there are a lot of options.\n", + "The ones you will probably use most often are:\n", + "- `linestyle`: how the line is plotted (set to '' to omit the line)\n", + "- `marker`: how the points are plotted (these are not plotted by default)\n", + "- `color`: what color to use (defaults to cycling through a set of 7 colors)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84b58452", + "metadata": {}, + "outputs": [], + "source": [ + "theta = np.linspace(0, 2 * np.pi, 101)\n", + "plt.plot(np.sin(theta), np.cos(theta))\n", + "plt.plot([-0.3, 0.3], [0.3, 0.3], marker='o', linestyle='', markersize=20)\n", + "plt.plot(0, -0.1, marker='s', color='black')\n", + "x = np.linspace(-0.5, 0.5, 5)\n", + "plt.plot(x, x ** 2 - 0.5, linestyle='--', marker='+', color='red')" + ] + }, + { + "cell_type": "markdown", + "id": "0d2e8301", + "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." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "10c2404c", + "metadata": {}, + "outputs": [], + "source": [ + "x = np.linspace(0, 1, 11)\n", + "plt.plot(x, x)\n", + "plt.plot(x, x ** 2, '--') # sets the linestyle to dashed\n", + "plt.plot(x, x ** 3, 's') # sets the marker to square (and turns off the line)\n", + "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": "1e340fc7", + "metadata": {}, + "source": [ + "### 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:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7f3852a6", + "metadata": {}, + "outputs": [], + "source": [ + "x = np.random.rand(30)\n", + "y = np.random.rand(30)\n", + "plt.scatter(x, y, x * 30, y)\n", + "plt.colorbar() # adds a colorbar" + ] + }, + { + "cell_type": "markdown", + "id": "dcb5d48c", + "metadata": {}, + "source": [ + "The third argument is the variable determining the size, while the fourth argument is the variable setting the color.\n", + "### Histograms and bar plots\n", + "For a simple histogram you can do this:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "50770a55", + "metadata": {}, + "outputs": [], + "source": [ + "r = np.random.rand(1000)\n", + "n,bins,_ = plt.hist((r-0.5)**2, bins=30)" + ] + }, + { + "cell_type": "markdown", + "id": "17bda7f4", + "metadata": {}, + "source": [ + "where it also returns the number of elements in each bin, as `n`, and\n", + "the bin centres, as `bins`.\n", + "\n", + "> The `_` in the third part on the left\n", + "> hand side is a shorthand for just throwing away the corresponding part\n", + "> of the return structure.\n", + "\n", + "\n", + "There is also a call for doing bar plots:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "85dbb204", + "metadata": {}, + "outputs": [], + "source": [ + "samp1 = r[0:10]\n", + "samp2 = r[10:20]\n", + "bwidth = 0.3\n", + "xcoord = np.arange(10)\n", + "plt.bar(xcoord-bwidth, samp1, width=bwidth, color='red', label='Sample 1')\n", + "plt.bar(xcoord, samp2, width=bwidth, color='blue', label='Sample 2')\n", + "plt.legend(loc='upper left')" + ] + }, + { + "cell_type": "markdown", + "id": "acbbe7b5", + "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", + "### 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`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e749b87e", + "metadata": {}, + "outputs": [], + "source": [ + "x = np.arange(5)\n", + "y1 = [0.3, 0.5, 0.7, 0.1, 0.3]\n", + "yerr = [0.12, 0.28, 0.1, 0.25, 0.6]\n", + "xerr = 0.3\n", + "plt.errorbar(x, y1, yerr, xerr, marker='s', linestyle='')" + ] + }, + { + "cell_type": "markdown", + "id": "33914264", + "metadata": {}, + "source": [ + "### Shading regions\n", + "An area below a plot can be shaded using `plt.fill`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "df50543b", + "metadata": {}, + "outputs": [], + "source": [ + "x = np.linspace(0, 2, 100)\n", + "plt.fill(x, np.sin(x * np.pi))" + ] + }, + { + "cell_type": "markdown", + "id": "068a8056", + "metadata": {}, + "source": [ + "This can be nicely combined with a polar projection, to create 2D orientation distribution functions:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3b75271e", + "metadata": {}, + "outputs": [], + "source": [ + "plt.subplot(projection='polar')\n", + "theta = np.linspace(0, 2 * np.pi, 100)\n", + "plt.fill(theta, np.exp(-2 * np.cos(theta) ** 2))" + ] + }, + { + "cell_type": "markdown", + "id": "fff9ddbe", + "metadata": {}, + "source": [ + "The area between two lines can be shaded using `fill_between`:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2bf5186f", + "metadata": {}, + "outputs": [], + "source": [ + "x = np.linspace(0, 10, 1000)\n", + "y = 5 * np.sin(5 * x) + x - 0.1 * x ** 2\n", + "yl = x - 0.1 * x ** 2 - 5\n", + "yu = yl + 10\n", + "plt.plot(x, y, 'r')\n", + "plt.fill_between(x, yl, yu)" + ] + }, + { + "cell_type": "markdown", + "id": "de59cfd2", + "metadata": {}, + "source": [ + "### 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)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c28e90a1", + "metadata": {}, + "outputs": [], + "source": [ + "import nibabel as nib\n", + "import os.path as op\n", + "nim = nib.load(op.expandvars('${FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'), mmap=False)\n", + "imdat = nim.get_data().astype(float)\n", + "imslc = imdat[:,:,70]\n", + "plt.imshow(imslc, cmap=plt.cm.gray)\n", + "plt.colorbar()\n", + "plt.grid('off')" + ] + }, + { + "cell_type": "markdown", + "id": "58546cf4", + "metadata": {}, + "source": [ + "Note that matplotlib will use the **voxel data orientation**, and that\n", + "configuring the plot orientation is **your responsibility**. To rotate a\n", + "slice, simply transpose the data (`.T`). To invert the data along along an\n", + "axis, you don't need to modify the data - simply swap the axis limits around:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a7004276", + "metadata": {}, + "outputs": [], + "source": [ + "plt.imshow(imslc.T, cmap=plt.cm.gray)\n", + "plt.xlim(reversed(plt.xlim()))\n", + "plt.ylim(reversed(plt.ylim()))\n", + "plt.colorbar()\n", + "plt.grid('off')" + ] + }, + { + "cell_type": "markdown", + "id": "1f36a7a9", + "metadata": {}, + "source": [ + "> It is easier to produce informative brain images using nilearn or fsleyes\n", + "### Adding lines, arrows, and text\n", + "Adding horizontal/vertical lines, arrows, and text:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f411a442", + "metadata": {}, + "outputs": [], + "source": [ + "plt.axhline(-1) # horizontal line\n", + "plt.axvline(1) # vertical line\n", + "plt.arrow(0.2, -0.2, 0.2, -0.8, length_includes_head=True, width=0.01)\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", + "[[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", + "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:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "081cb8b8", + "metadata": {}, + "outputs": [], + "source": [ + "np.random.seed(1)\n", + "fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)\n", + "for ax in axes.flat:\n", + " offset = np.random.rand(2) * 5\n", + " ax.scatter(np.random.randn(10) + offset[0], np.random.randn(10) + offset[1])\n", + "fig.suptitle(\"group of plots, sharing x- and y-axes\")\n", + "fig.subplots_adjust(wspace=0, hspace=0, top=0.9)" + ] + }, + { + "cell_type": "markdown", + "id": "dd3db134", + "metadata": {}, + "source": [ + "### 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:" + ] + }, + { + "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", + "\n", + "For example:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6ffd540c", + "metadata": {}, + "outputs": [], + "source": [ + "fig, axes = plt.subplots()\n", + "axes.errorbar([0, 1, 2], [0.8, 0.4, -0.2], 0.1, linestyle='-', marker='s')\n", + "axes.set_xticks((0, 1, 2))\n", + "axes.set_xticklabels(('start', 'middle', 'end'))\n", + "for tick in axes.get_xticklabels():\n", + " tick.set(\n", + " rotation=45,\n", + " size='larger'\n", + " )\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 +} diff --git a/applications/plotting/matplotlib.md b/applications/plotting/matplotlib.md index a2f62e9..ff3133e 100644 --- a/applications/plotting/matplotlib.md +++ b/applications/plotting/matplotlib.md @@ -32,34 +32,34 @@ plt.plot? 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 None to omit the line) +- `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) ``` 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=None, size=10) -plt.plot(0, 0.1, marker='s', color='black') -plt.plot(0.5 * x, -0.5 * x ** 2 - 0.5, linestyle='--', marker='+', color='yellow') +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') ``` -Because these keywords are so common, you can actually set them directly by passing in a string as the third argument. +Because these keywords are so common, you can actually set one or more of them by passing in a string as the third argument. ``` x = np.linspace(0, 1, 11) plt.plot(x, x) -plt.plot(x, x, '--') # sets the linestyle to dashed -plt.plot(x, x, 's') # sets the marker to square (and turns off the line) -plt.plot(x, x, 'y:') # sets the linestyle to dotted (i.e., ':') and the color to yellow (i.e., 'y') +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') ``` -Note in the last line that if you want to define both the color and the marker/linestyle you need to put the color identifier first. ### 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: ``` x = np.random.rand(30) y = np.random.rand(30) -plt.scatter(x, y, x, y) +plt.scatter(x, y, x * 30, y) plt.colorbar() # adds a colorbar ``` -The third argument is the variable determining the color, while the fourth argument is the variable setting the size. +The third argument is the variable determining the size, while the fourth argument is the variable setting the color. ### Histograms and bar plots For a simple histogram you can do this: ``` @@ -85,7 +85,7 @@ plt.bar(xcoord, samp2, width=bwidth, color='blue', label='Sample 2') 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) 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 If your data is not completely perfect and has for some obscure reason some uncertainty associated with it, @@ -95,7 +95,7 @@ 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.error(x, y1, yerr, xerr, marker='s') +plt.errorbar(x, y1, yerr, xerr, marker='s', linestyle='') ``` ### Shading regions An area below a plot can be shaded using `plt.fill` @@ -104,19 +104,19 @@ x = np.linspace(0, 2, 100) plt.fill(x, np.sin(x * np.pi)) ``` -This can be nicely combined with a polar projection, to create nice polar plots: +This can be nicely combined with a polar projection, to create 2D orientation distribution functions: ``` -plt.subplot(project='polar') +plt.subplot(projection='polar') theta = np.linspace(0, 2 * np.pi, 100) plt.fill(theta, np.exp(-2 * np.cos(theta) ** 2)) ``` The area between two lines can be shaded using `fill_between`: ``` -x = np.linspace(0, 10, 100) -y = 5 * np.sin(x) + x - 0.1 * x ** 2 -yl = x - 0.1 * x ** 2 - 2.5 -yu = yl + 5 +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) ``` @@ -148,14 +148,16 @@ plt.ylim(reversed(plt.ylim())) plt.colorbar() plt.grid('off') ``` + +> It is easier to produce informative brain images using nilearn or fsleyes ### Adding lines, arrows, and text Adding horizontal/vertical lines, arrows, and text: ``` plt.axhline(-1) # horizontal line plt.axvline(1) # vertical line -plt.arrow(0.2, -0.2, 0.2, -0.8, length_includes_head=True) -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) +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 ``` 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 @@ -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])` 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. +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. @@ -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) ### 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: ``` -np.random.seed(1) fig, axes = plt.subplots(nrows=2, ncols=2) -for ax in axes.flat: - ax.scatter(np.random.randn(10), np.random.randn(10)) - ax.set( - title='long multi-\nline title', - xlabel='x-label', - ylabel='y-label', - ) -#fig.tight_layout() +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() ``` 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). @@ -239,10 +237,10 @@ For example, we can remove any whitespace between the plots using: np.random.seed(1) fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True) for ax in axes.flat: - offset = np.random.rand(2) + offset = np.random.rand(2) * 5 ax.scatter(np.random.randn(10) + offset[0], np.random.randn(10) + offset[1]) -fig.set_suptitle("group of plots, where each row shares the x-axis and each column the y-axis") -fig.subplots_adjust(width=0, height=0, top=0.9) +fig.suptitle("group of plots, sharing x- and y-axes") +fig.subplots_adjust(wspace=0, hspace=0, top=0.9) ``` ### Advanced grid configurations (GridSpec) @@ -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. -You can edit the font of the text either when setting the label or after the fact. -As an example, here are three ways to change the label colours: +You can edit the font of the text when setting the label: ``` fig, axes = plt.subplots() axes.plot([1, 2, 3], [2.3, 4.1, 0.8]) -axes.set_xlabel("xlabel", color='red') # set color when setting text label -label = axes.set_ylabel("ylabel") # keep track of the Text object returned by `set_?` -label.set_color('blue') -axes.set_title("title") -axes.get_title().set_color('green') # use `get_?` to get the Text object after the fact +axes.set_xlabel("xlabel", color='red') +axes.set_ylabel("ylabel", fontsize='larger') ``` ### 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). +- 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). For example: ``` fig, axes = plt.subplots() -axes.error([0, 1, 2], [0.8, 0.4, -0.2], 0.1, linestyle='0', marker='s') +axes.errorbar([0, 1, 2], [0.8, 0.4, -0.2], 0.1, linestyle='-', marker='s') axes.set_xticks((0, 1, 2)) axes.set_xticklabels(('start', 'middle', 'end')) -for tick in axes.get_ticks(): - tick.set_rotation(45) +for tick in axes.get_xticklabels(): + tick.set( + rotation=45, + size='larger' + ) axes.set_xlabel("Progression through practical") axes.set_yticks((0, 0.5, 1)) axes.set_yticklabels(('0', '50%', '100%')) +fig.tight_layout() ``` ## FAQ ### Why am I getting two images? -- GitLab From bea989b4f9975569b219abdf6c250d48ad4aa08a Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Mon, 26 Apr 2021 15:08:51 +0100 Subject: [PATCH 4/9] added table of contents --- applications/plotting/matplotlib.ipynb | 180 +++++++++++++++++-------- applications/plotting/matplotlib.md | 50 ++++++- 2 files changed, 168 insertions(+), 62 deletions(-) diff --git a/applications/plotting/matplotlib.ipynb b/applications/plotting/matplotlib.ipynb index 20e6d5c..9e53f07 100644 --- a/applications/plotting/matplotlib.ipynb +++ b/applications/plotting/matplotlib.ipynb @@ -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", + "\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": [ + "\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": [ + "\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", + "\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", + "\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": [ + "\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": [ + "\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", + "\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", + "\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", + "\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", + "\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": [ + "\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": [ + "\n", "## Styling your plot\n", + "\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": [ + "\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": [ + "\n", "## FAQ\n", + "\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", + "\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", + "\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 } diff --git a/applications/plotting/matplotlib.md b/applications/plotting/matplotlib.md index ff3133e..39596e3 100644 --- a/applications/plotting/matplotlib.md +++ b/applications/plotting/matplotlib.md @@ -1,4 +1,4 @@ -# Plotting with python +# Matplotlib tutorial The main plotting library in python is `matplotlib`. It provides a simple interface to just explore the data, @@ -13,12 +13,34 @@ 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) + + ## Basic plotting commands Let's start with the basic imports: ``` import matplotlib.pyplot as plt import numpy as np ``` + ### 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') ``` + ### 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. + ### 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. + ### 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`: @@ -97,6 +122,7 @@ yerr = [0.12, 0.28, 0.1, 0.25, 0.6] xerr = 0.3 plt.errorbar(x, y1, yerr, xerr, marker='s', linestyle='') ``` + ### Shading regions 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) ``` + ### 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 + ### 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. + ## 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. + + ## 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) + ### 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) ``` + ### 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: @@ -261,7 +294,9 @@ f3_ax5 = fig.add_subplot(gs[-1, -2]) f3_ax5.set_title('gs[-1, -2]') ``` + ## 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: @@ -293,6 +328,7 @@ axes.set_xlabel("xlabel", color='red') axes.set_ylabel("ylabel", fontsize='larger') ``` + ### Editing the x- and y-axis We can change many of the properties of the x- and y-axis by using `set_` commands. @@ -319,14 +355,22 @@ axes.set_yticks((0, 0.5, 1)) axes.set_yticklabels(('0', '50%', '100%')) fig.tight_layout() ``` + ## FAQ + ### Why am I getting two images? -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. + + ### 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 + +### 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. -- GitLab From e8296319fcd32e68a152afc2b06d3b829b2bc4b6 Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Mon, 26 Apr 2021 16:53:44 +0100 Subject: [PATCH 5/9] Fix the link to the anatomy of a plot figure --- applications/plotting/matplotlib.ipynb | 116 +++++++++++++------------ applications/plotting/matplotlib.md | 6 +- 2 files changed, 63 insertions(+), 59 deletions(-) diff --git a/applications/plotting/matplotlib.ipynb b/applications/plotting/matplotlib.ipynb index 9e53f07..3875941 100644 --- a/applications/plotting/matplotlib.ipynb +++ b/applications/plotting/matplotlib.ipynb @@ -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": [ "\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": [ "\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": [ "\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": [ "\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": [ "\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": [ "\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": [ "\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": [ "\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", diff --git a/applications/plotting/matplotlib.md b/applications/plotting/matplotlib.md index 39596e3..5109280 100644 --- a/applications/plotting/matplotlib.md +++ b/applications/plotting/matplotlib.md @@ -198,8 +198,10 @@ for more detail. 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()`. -- GitLab From 96f3b243425e9f2631b31223e332293c827cbced Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Mon, 26 Apr 2021 17:13:16 +0100 Subject: [PATCH 6/9] Explain plt.getp --- applications/plotting/matplotlib.ipynb | 195 +++++++++++++++---------- applications/plotting/matplotlib.md | 25 +++- 2 files changed, 142 insertions(+), 78 deletions(-) diff --git a/applications/plotting/matplotlib.ipynb b/applications/plotting/matplotlib.ipynb index 3875941..a45e684 100644 --- a/applications/plotting/matplotlib.ipynb +++ b/applications/plotting/matplotlib.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "christian-smart", + "id": "5567ba9e", "metadata": {}, "source": [ "# Matplotlib tutorial\n", @@ -48,7 +48,7 @@ { "cell_type": "code", "execution_count": null, - "id": "quick-postage", + "id": "3917392c", "metadata": {}, "outputs": [], "source": [ @@ -58,7 +58,7 @@ }, { "cell_type": "markdown", - "id": "prescribed-writing", + "id": "76688c00", "metadata": {}, "source": [ "\n", @@ -69,7 +69,7 @@ { "cell_type": "code", "execution_count": null, - "id": "turkish-marsh", + "id": "00d5ff18", "metadata": {}, "outputs": [], "source": [ @@ -78,7 +78,7 @@ }, { "cell_type": "markdown", - "id": "compact-modeling", + "id": "3d0472b7", "metadata": {}, "source": [ "To adjust how the line is plotted, check the documentation:" @@ -87,7 +87,7 @@ { "cell_type": "code", "execution_count": null, - "id": "distinct-coordinate", + "id": "38d3f3ab", "metadata": {}, "outputs": [], "source": [ @@ -96,7 +96,7 @@ }, { "cell_type": "markdown", - "id": "green-dutch", + "id": "867ea1f5", "metadata": {}, "source": [ "As you can see there are a lot of options.\n", @@ -109,7 +109,7 @@ { "cell_type": "code", "execution_count": null, - "id": "adjacent-satellite", + "id": "c705366a", "metadata": {}, "outputs": [], "source": [ @@ -123,7 +123,7 @@ }, { "cell_type": "markdown", - "id": "external-meaning", + "id": "f7e493a7", "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": "simple-korean", + "id": "c2b6c5c5", "metadata": {}, "outputs": [], "source": [ @@ -145,7 +145,7 @@ }, { "cell_type": "markdown", - "id": "pediatric-sullivan", + "id": "c7dd3aa9", "metadata": {}, "source": [ "\n", @@ -156,7 +156,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bright-preparation", + "id": "33b81ef4", "metadata": {}, "outputs": [], "source": [ @@ -168,7 +168,7 @@ }, { "cell_type": "markdown", - "id": "asian-mailing", + "id": "22de1aac", "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": "massive-relative", + "id": "0c445269", "metadata": {}, "outputs": [], "source": [ @@ -190,7 +190,7 @@ }, { "cell_type": "markdown", - "id": "positive-insight", + "id": "41a54dd8", "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": "intensive-taste", + "id": "9d7c817d", "metadata": {}, "outputs": [], "source": [ @@ -222,7 +222,7 @@ }, { "cell_type": "markdown", - "id": "boolean-metropolitan", + "id": "eca1cea7", "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": "basic-cambridge", + "id": "939fcf82", "metadata": {}, "outputs": [], "source": [ @@ -249,7 +249,7 @@ }, { "cell_type": "markdown", - "id": "twelve-assist", + "id": "cb1a8d17", "metadata": {}, "source": [ "\n", @@ -260,7 +260,7 @@ { "cell_type": "code", "execution_count": null, - "id": "stuck-teaching", + "id": "f7221bc3", "metadata": {}, "outputs": [], "source": [ @@ -270,7 +270,7 @@ }, { "cell_type": "markdown", - "id": "metric-chemical", + "id": "86d77cf6", "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": "democratic-israel", + "id": "b96cbc10", "metadata": {}, "outputs": [], "source": [ @@ -290,7 +290,7 @@ }, { "cell_type": "markdown", - "id": "connected-consideration", + "id": "5a0defe8", "metadata": {}, "source": [ "The area between two lines can be shaded using `fill_between`:" @@ -299,7 +299,7 @@ { "cell_type": "code", "execution_count": null, - "id": "engaged-lottery", + "id": "3f11d97b", "metadata": {}, "outputs": [], "source": [ @@ -313,7 +313,7 @@ }, { "cell_type": "markdown", - "id": "paperback-stylus", + "id": "aa3fb87b", "metadata": {}, "source": [ "\n", @@ -324,7 +324,7 @@ { "cell_type": "code", "execution_count": null, - "id": "acoustic-kitchen", + "id": "63f18c75", "metadata": {}, "outputs": [], "source": [ @@ -340,7 +340,7 @@ }, { "cell_type": "markdown", - "id": "frank-master", + "id": "be2facc0", "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": "initial-passing", + "id": "1a960ddf", "metadata": {}, "outputs": [], "source": [ @@ -365,7 +365,7 @@ }, { "cell_type": "markdown", - "id": "specialized-maintenance", + "id": "070f5772", "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": "weighted-publicity", + "id": "c7f6c0f6", "metadata": {}, "outputs": [], "source": [ @@ -390,7 +390,7 @@ }, { "cell_type": "markdown", - "id": "manual-bacon", + "id": "de291180", "metadata": {}, "source": [ "By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),\n", @@ -425,7 +425,7 @@ { "cell_type": "code", "execution_count": null, - "id": "earned-anaheim", + "id": "3d3482ef", "metadata": {}, "outputs": [], "source": [ @@ -436,7 +436,7 @@ }, { "cell_type": "markdown", - "id": "valued-hungary", + "id": "4923481d", "metadata": {}, "source": [ "Note that here we explicitly create the figure and add a single sub-plot to the figure.\n", @@ -444,6 +444,48 @@ "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", + "`plt.getp` gives a helpful summary of the properties of a matplotlib object (and what you might change):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c0c64d42", + "metadata": {}, + "outputs": [], + "source": [ + "plt.getp(ax)" + ] + }, + { + "cell_type": "markdown", + "id": "76b789ab", + "metadata": {}, + "source": [ + "When going through this list carefully you might have spotted that the plotted line is stored in the `lines` property.\n", + "Let's have a look at this line in more detail" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "02f9cb81", + "metadata": {}, + "outputs": [], + "source": [ + "plt.getp(ax.lines[0])" + ] + }, + { + "cell_type": "markdown", + "id": "9a192752", + "metadata": {}, + "source": [ + "This shows us all the properties stored about this line,\n", + "including its coordinates in many different formats \n", + "(`data`, `path`, `xdata`, `ydata`, or `xydata`),\n", + "the line style and width (`linestyle`, `linewidth`), `color`, etc.\n", + "\n", "\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", @@ -453,7 +495,7 @@ { "cell_type": "code", "execution_count": null, - "id": "intensive-bruce", + "id": "3cafa27a", "metadata": {}, "outputs": [], "source": [ @@ -469,7 +511,7 @@ }, { "cell_type": "markdown", - "id": "upset-stanley", + "id": "51141fee", "metadata": {}, "source": [ "For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the\n", @@ -481,7 +523,7 @@ { "cell_type": "code", "execution_count": null, - "id": "frank-treatment", + "id": "a7a6b2c7", "metadata": {}, "outputs": [], "source": [ @@ -494,7 +536,7 @@ }, { "cell_type": "markdown", - "id": "occupational-astronomy", + "id": "a1ec90e2", "metadata": {}, "source": [ "Here we use `plt.subplots`, which creates both a new figure for us and a grid of sub-plots. \n", @@ -509,7 +551,7 @@ { "cell_type": "code", "execution_count": null, - "id": "joint-chick", + "id": "0a5f85cc", "metadata": {}, "outputs": [], "source": [ @@ -523,7 +565,7 @@ }, { "cell_type": "markdown", - "id": "illegal-spanish", + "id": "ab07e5ab", "metadata": {}, "source": [ "Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.\n", @@ -534,7 +576,7 @@ { "cell_type": "code", "execution_count": null, - "id": "accomplished-watershed", + "id": "8e420304", "metadata": {}, "outputs": [], "source": [ @@ -549,7 +591,7 @@ }, { "cell_type": "markdown", - "id": "standing-course", + "id": "260dc7eb", "metadata": {}, "source": [ "\n", @@ -561,7 +603,7 @@ { "cell_type": "code", "execution_count": null, - "id": "silent-voluntary", + "id": "f58613d6", "metadata": {}, "outputs": [], "source": [ @@ -581,7 +623,7 @@ }, { "cell_type": "markdown", - "id": "roman-discharge", + "id": "cf0ef5c8", "metadata": {}, "source": [ "\n", @@ -595,7 +637,7 @@ { "cell_type": "code", "execution_count": null, - "id": "english-yahoo", + "id": "6f49e003", "metadata": {}, "outputs": [], "source": [ @@ -608,7 +650,7 @@ }, { "cell_type": "markdown", - "id": "constant-evolution", + "id": "d1c2e77c", "metadata": {}, "source": [ "You can also set any of these properties by calling `Axes.set` directly:" @@ -617,7 +659,7 @@ { "cell_type": "code", "execution_count": null, - "id": "suspended-biography", + "id": "5d744cf1", "metadata": {}, "outputs": [], "source": [ @@ -632,30 +674,31 @@ }, { "cell_type": "markdown", - "id": "annual-hundred", + "id": "9e621844", "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:" + "You can edit the font of the text when setting the label or after the fact using the object-oriented interface:" ] }, { "cell_type": "code", "execution_count": null, - "id": "trained-mouse", + "id": "389a85ff", "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')" + "axes.set_ylabel(\"ylabel\")\n", + "axes.get_yaxis().get_label().set_fontsize('larger')" ] }, { "cell_type": "markdown", - "id": "elementary-mentor", + "id": "c7612d2c", "metadata": {}, "source": [ "\n", @@ -674,7 +717,7 @@ { "cell_type": "code", "execution_count": null, - "id": "capital-surgeon", + "id": "0b91948e", "metadata": {}, "outputs": [], "source": [ @@ -695,7 +738,25 @@ }, { "cell_type": "markdown", - "id": "discrete-hartford", + "id": "3d5db817", + "metadata": {}, + "source": [ + "As illustrated earlier, we can get a more complete list of the things we could change about the x-axis by looking at its properties:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ca4c208f", + "metadata": {}, + "outputs": [], + "source": [ + "plt.getp(axes.get_xlabel())" + ] + }, + { + "cell_type": "markdown", + "id": "61b4f566", "metadata": {}, "source": [ "\n", @@ -727,7 +788,7 @@ { "cell_type": "code", "execution_count": null, - "id": "fifty-relaxation", + "id": "33900afe", "metadata": {}, "outputs": [], "source": [ @@ -736,7 +797,7 @@ }, { "cell_type": "markdown", - "id": "fifty-sunglasses", + "id": "7273f530", "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", @@ -747,7 +808,7 @@ { "cell_type": "code", "execution_count": null, - "id": "underlying-dealer", + "id": "b50352a0", "metadata": {}, "outputs": [], "source": [ @@ -757,7 +818,7 @@ }, { "cell_type": "markdown", - "id": "general-subscriber", + "id": "2a436f07", "metadata": {}, "source": [ "Usually, the default backend will be fine, so you will not have to set it. \n", @@ -765,25 +826,7 @@ ] } ], - "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" - } - }, + "metadata": {}, "nbformat": 4, "nbformat_minor": 5 } diff --git a/applications/plotting/matplotlib.md b/applications/plotting/matplotlib.md index 5109280..d2bd9c7 100644 --- a/applications/plotting/matplotlib.md +++ b/applications/plotting/matplotlib.md @@ -224,6 +224,20 @@ 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. +`plt.getp` gives a helpful summary of the properties of a matplotlib object (and what you might change): +``` +plt.getp(ax) +``` +When going through this list carefully you might have spotted that the plotted line is stored in the `lines` property. +Let's have a look at this line in more detail +``` +plt.getp(ax.lines[0]) +``` +This shows us all the properties stored about this line, +including its coordinates in many different formats +(`data`, `path`, `xdata`, `ydata`, or `xydata`), +the line style and width (`linestyle`, `linewidth`), `color`, etc. + ## 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. @@ -322,12 +336,13 @@ 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. -You can edit the font of the text when setting the label: +You can edit the font of the text when setting the label or after the fact using the object-oriented interface: ``` 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') +axes.set_ylabel("ylabel") +axes.get_yaxis().get_label().set_fontsize('larger') ``` @@ -357,6 +372,12 @@ axes.set_yticks((0, 0.5, 1)) axes.set_yticklabels(('0', '50%', '100%')) fig.tight_layout() ``` + +As illustrated earlier, we can get a more complete list of the things we could change about the x-axis by looking at its properties: +``` +plt.getp(axes.get_xlabel()) +``` + ## FAQ -- GitLab From 8ecc39a4b0897356aff04038fc93d74b623d1d35 Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Mon, 26 Apr 2021 17:15:42 +0100 Subject: [PATCH 7/9] added link to artist tutorial --- applications/plotting/matplotlib.ipynb | 124 ++++++++++++------------- applications/plotting/matplotlib.md | 2 +- 2 files changed, 63 insertions(+), 63 deletions(-) diff --git a/applications/plotting/matplotlib.ipynb b/applications/plotting/matplotlib.ipynb index a45e684..022dc9e 100644 --- a/applications/plotting/matplotlib.ipynb +++ b/applications/plotting/matplotlib.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "5567ba9e", + "id": "4ba14387", "metadata": {}, "source": [ "# Matplotlib tutorial\n", @@ -48,7 +48,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3917392c", + "id": "3f5212f2", "metadata": {}, "outputs": [], "source": [ @@ -58,7 +58,7 @@ }, { "cell_type": "markdown", - "id": "76688c00", + "id": "9b66b866", "metadata": {}, "source": [ "\n", @@ -69,7 +69,7 @@ { "cell_type": "code", "execution_count": null, - "id": "00d5ff18", + "id": "520e577b", "metadata": {}, "outputs": [], "source": [ @@ -78,7 +78,7 @@ }, { "cell_type": "markdown", - "id": "3d0472b7", + "id": "88a5db94", "metadata": {}, "source": [ "To adjust how the line is plotted, check the documentation:" @@ -87,7 +87,7 @@ { "cell_type": "code", "execution_count": null, - "id": "38d3f3ab", + "id": "ba7b1bf7", "metadata": {}, "outputs": [], "source": [ @@ -96,7 +96,7 @@ }, { "cell_type": "markdown", - "id": "867ea1f5", + "id": "1eb64212", "metadata": {}, "source": [ "As you can see there are a lot of options.\n", @@ -109,7 +109,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c705366a", + "id": "b0571451", "metadata": {}, "outputs": [], "source": [ @@ -123,7 +123,7 @@ }, { "cell_type": "markdown", - "id": "f7e493a7", + "id": "85597103", "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": "c2b6c5c5", + "id": "e8c50bcf", "metadata": {}, "outputs": [], "source": [ @@ -145,7 +145,7 @@ }, { "cell_type": "markdown", - "id": "c7dd3aa9", + "id": "84e7d60e", "metadata": {}, "source": [ "\n", @@ -156,7 +156,7 @@ { "cell_type": "code", "execution_count": null, - "id": "33b81ef4", + "id": "fff43424", "metadata": {}, "outputs": [], "source": [ @@ -168,7 +168,7 @@ }, { "cell_type": "markdown", - "id": "22de1aac", + "id": "ed3c393d", "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": "0c445269", + "id": "87e83be8", "metadata": {}, "outputs": [], "source": [ @@ -190,7 +190,7 @@ }, { "cell_type": "markdown", - "id": "41a54dd8", + "id": "78abc3b7", "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": "9d7c817d", + "id": "b2945a9f", "metadata": {}, "outputs": [], "source": [ @@ -222,7 +222,7 @@ }, { "cell_type": "markdown", - "id": "eca1cea7", + "id": "09f070f4", "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": "939fcf82", + "id": "79fb7453", "metadata": {}, "outputs": [], "source": [ @@ -249,7 +249,7 @@ }, { "cell_type": "markdown", - "id": "cb1a8d17", + "id": "d54c0bbc", "metadata": {}, "source": [ "\n", @@ -260,7 +260,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f7221bc3", + "id": "599096f8", "metadata": {}, "outputs": [], "source": [ @@ -270,7 +270,7 @@ }, { "cell_type": "markdown", - "id": "86d77cf6", + "id": "369696fa", "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": "b96cbc10", + "id": "b97730b0", "metadata": {}, "outputs": [], "source": [ @@ -290,7 +290,7 @@ }, { "cell_type": "markdown", - "id": "5a0defe8", + "id": "049fbd3b", "metadata": {}, "source": [ "The area between two lines can be shaded using `fill_between`:" @@ -299,7 +299,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3f11d97b", + "id": "672b1757", "metadata": {}, "outputs": [], "source": [ @@ -313,7 +313,7 @@ }, { "cell_type": "markdown", - "id": "aa3fb87b", + "id": "e866c409", "metadata": {}, "source": [ "\n", @@ -324,7 +324,7 @@ { "cell_type": "code", "execution_count": null, - "id": "63f18c75", + "id": "42fc8081", "metadata": {}, "outputs": [], "source": [ @@ -340,7 +340,7 @@ }, { "cell_type": "markdown", - "id": "be2facc0", + "id": "83fb2bb3", "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": "1a960ddf", + "id": "8aa53d09", "metadata": {}, "outputs": [], "source": [ @@ -365,7 +365,7 @@ }, { "cell_type": "markdown", - "id": "070f5772", + "id": "43fce6ce", "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": "c7f6c0f6", + "id": "37c81436", "metadata": {}, "outputs": [], "source": [ @@ -390,7 +390,7 @@ }, { "cell_type": "markdown", - "id": "de291180", + "id": "40daff02", "metadata": {}, "source": [ "By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),\n", @@ -402,7 +402,7 @@ "\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", + "(collectively called [artists](https://matplotlib.org/stable/tutorials/intermediate/artists.html) in matplotlib) to a single plot.\n", "To prettify this plots, we first need to know what all the features are called:\n", "\n", "![anatomy of a plot](https://matplotlib.org/stable/_images/anatomy.png)\n", @@ -425,7 +425,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3d3482ef", + "id": "660d1559", "metadata": {}, "outputs": [], "source": [ @@ -436,7 +436,7 @@ }, { "cell_type": "markdown", - "id": "4923481d", + "id": "2ad9cfbf", "metadata": {}, "source": [ "Note that here we explicitly create the figure and add a single sub-plot to the figure.\n", @@ -450,7 +450,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c0c64d42", + "id": "7be3b246", "metadata": {}, "outputs": [], "source": [ @@ -459,7 +459,7 @@ }, { "cell_type": "markdown", - "id": "76b789ab", + "id": "7fbf6acd", "metadata": {}, "source": [ "When going through this list carefully you might have spotted that the plotted line is stored in the `lines` property.\n", @@ -469,7 +469,7 @@ { "cell_type": "code", "execution_count": null, - "id": "02f9cb81", + "id": "80481e71", "metadata": {}, "outputs": [], "source": [ @@ -478,7 +478,7 @@ }, { "cell_type": "markdown", - "id": "9a192752", + "id": "fa8e6fee", "metadata": {}, "source": [ "This shows us all the properties stored about this line,\n", @@ -495,7 +495,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3cafa27a", + "id": "83b536d2", "metadata": {}, "outputs": [], "source": [ @@ -511,7 +511,7 @@ }, { "cell_type": "markdown", - "id": "51141fee", + "id": "3438c4f7", "metadata": {}, "source": [ "For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the\n", @@ -523,7 +523,7 @@ { "cell_type": "code", "execution_count": null, - "id": "a7a6b2c7", + "id": "4731d436", "metadata": {}, "outputs": [], "source": [ @@ -536,7 +536,7 @@ }, { "cell_type": "markdown", - "id": "a1ec90e2", + "id": "bca7abe6", "metadata": {}, "source": [ "Here we use `plt.subplots`, which creates both a new figure for us and a grid of sub-plots. \n", @@ -551,7 +551,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0a5f85cc", + "id": "83fab131", "metadata": {}, "outputs": [], "source": [ @@ -565,7 +565,7 @@ }, { "cell_type": "markdown", - "id": "ab07e5ab", + "id": "609cdb3f", "metadata": {}, "source": [ "Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.\n", @@ -576,7 +576,7 @@ { "cell_type": "code", "execution_count": null, - "id": "8e420304", + "id": "972fda35", "metadata": {}, "outputs": [], "source": [ @@ -591,7 +591,7 @@ }, { "cell_type": "markdown", - "id": "260dc7eb", + "id": "18d903e1", "metadata": {}, "source": [ "\n", @@ -603,7 +603,7 @@ { "cell_type": "code", "execution_count": null, - "id": "f58613d6", + "id": "e98b00c8", "metadata": {}, "outputs": [], "source": [ @@ -623,7 +623,7 @@ }, { "cell_type": "markdown", - "id": "cf0ef5c8", + "id": "0d363e0e", "metadata": {}, "source": [ "\n", @@ -637,7 +637,7 @@ { "cell_type": "code", "execution_count": null, - "id": "6f49e003", + "id": "9553b91a", "metadata": {}, "outputs": [], "source": [ @@ -650,7 +650,7 @@ }, { "cell_type": "markdown", - "id": "d1c2e77c", + "id": "79b53065", "metadata": {}, "source": [ "You can also set any of these properties by calling `Axes.set` directly:" @@ -659,7 +659,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5d744cf1", + "id": "97643220", "metadata": {}, "outputs": [], "source": [ @@ -674,7 +674,7 @@ }, { "cell_type": "markdown", - "id": "9e621844", + "id": "e2fbb884", "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", @@ -685,7 +685,7 @@ { "cell_type": "code", "execution_count": null, - "id": "389a85ff", + "id": "5f16a656", "metadata": {}, "outputs": [], "source": [ @@ -698,7 +698,7 @@ }, { "cell_type": "markdown", - "id": "c7612d2c", + "id": "f69eb693", "metadata": {}, "source": [ "\n", @@ -717,7 +717,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0b91948e", + "id": "b2d196a9", "metadata": {}, "outputs": [], "source": [ @@ -738,7 +738,7 @@ }, { "cell_type": "markdown", - "id": "3d5db817", + "id": "c4c35f2a", "metadata": {}, "source": [ "As illustrated earlier, we can get a more complete list of the things we could change about the x-axis by looking at its properties:" @@ -747,7 +747,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ca4c208f", + "id": "ab2633a6", "metadata": {}, "outputs": [], "source": [ @@ -756,7 +756,7 @@ }, { "cell_type": "markdown", - "id": "61b4f566", + "id": "440d18ce", "metadata": {}, "source": [ "\n", @@ -788,7 +788,7 @@ { "cell_type": "code", "execution_count": null, - "id": "33900afe", + "id": "93dbeb6e", "metadata": {}, "outputs": [], "source": [ @@ -797,7 +797,7 @@ }, { "cell_type": "markdown", - "id": "7273f530", + "id": "d53eef2b", "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", @@ -808,7 +808,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b50352a0", + "id": "c16b4394", "metadata": {}, "outputs": [], "source": [ @@ -818,7 +818,7 @@ }, { "cell_type": "markdown", - "id": "2a436f07", + "id": "96529a3c", "metadata": {}, "source": [ "Usually, the default backend will be fine, so you will not have to set it. \n", diff --git a/applications/plotting/matplotlib.md b/applications/plotting/matplotlib.md index d2bd9c7..cb93644 100644 --- a/applications/plotting/matplotlib.md +++ b/applications/plotting/matplotlib.md @@ -196,7 +196,7 @@ 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. +(collectively called [artists](https://matplotlib.org/stable/tutorials/intermediate/artists.html) in matplotlib) to a single plot. To prettify this plots, we first need to know what all the features are called: ![anatomy of a plot](https://matplotlib.org/stable/_images/anatomy.png) -- GitLab From fbd8ae169ce420b063f3e6d83f3ad373e627f6ec Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Tue, 27 Apr 2021 10:39:57 +0100 Subject: [PATCH 8/9] Bug fixes/changes suggested by Mo --- applications/plotting/matplotlib.ipynb | 130 ++++++++++++------------- applications/plotting/matplotlib.md | 8 +- getting_started/06_plotting.ipynb | 36 ++++++- getting_started/06_plotting.md | 4 +- 4 files changed, 104 insertions(+), 74 deletions(-) diff --git a/applications/plotting/matplotlib.ipynb b/applications/plotting/matplotlib.ipynb index 022dc9e..921bfcf 100644 --- a/applications/plotting/matplotlib.ipynb +++ b/applications/plotting/matplotlib.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "4ba14387", + "id": "dda775e0", "metadata": {}, "source": [ "# Matplotlib tutorial\n", @@ -48,7 +48,7 @@ { "cell_type": "code", "execution_count": null, - "id": "3f5212f2", + "id": "5ccc9a73", "metadata": {}, "outputs": [], "source": [ @@ -58,7 +58,7 @@ }, { "cell_type": "markdown", - "id": "9b66b866", + "id": "ed561bcb", "metadata": {}, "source": [ "\n", @@ -69,7 +69,7 @@ { "cell_type": "code", "execution_count": null, - "id": "520e577b", + "id": "80e15ee1", "metadata": {}, "outputs": [], "source": [ @@ -78,7 +78,7 @@ }, { "cell_type": "markdown", - "id": "88a5db94", + "id": "c2923739", "metadata": {}, "source": [ "To adjust how the line is plotted, check the documentation:" @@ -87,7 +87,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ba7b1bf7", + "id": "0ce4a966", "metadata": {}, "outputs": [], "source": [ @@ -96,7 +96,7 @@ }, { "cell_type": "markdown", - "id": "1eb64212", + "id": "e7263d90", "metadata": {}, "source": [ "As you can see there are a lot of options.\n", @@ -109,7 +109,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b0571451", + "id": "dfbbb093", "metadata": {}, "outputs": [], "source": [ @@ -123,7 +123,7 @@ }, { "cell_type": "markdown", - "id": "85597103", + "id": "c5cf861d", "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": "e8c50bcf", + "id": "9446bd5b", "metadata": {}, "outputs": [], "source": [ @@ -145,7 +145,7 @@ }, { "cell_type": "markdown", - "id": "84e7d60e", + "id": "f17ba1d2", "metadata": {}, "source": [ "\n", @@ -156,7 +156,7 @@ { "cell_type": "code", "execution_count": null, - "id": "fff43424", + "id": "31c06d59", "metadata": {}, "outputs": [], "source": [ @@ -168,7 +168,7 @@ }, { "cell_type": "markdown", - "id": "ed3c393d", + "id": "777734ae", "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": "87e83be8", + "id": "1fd95cae", "metadata": {}, "outputs": [], "source": [ @@ -190,7 +190,7 @@ }, { "cell_type": "markdown", - "id": "78abc3b7", + "id": "72a015c6", "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": "b2945a9f", + "id": "0c410bcd", "metadata": {}, "outputs": [], "source": [ @@ -222,7 +222,7 @@ }, { "cell_type": "markdown", - "id": "09f070f4", + "id": "75c96456", "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": "79fb7453", + "id": "00caf192", "metadata": {}, "outputs": [], "source": [ @@ -249,7 +249,7 @@ }, { "cell_type": "markdown", - "id": "d54c0bbc", + "id": "dd9fb30f", "metadata": {}, "source": [ "\n", @@ -260,7 +260,7 @@ { "cell_type": "code", "execution_count": null, - "id": "599096f8", + "id": "bb53b679", "metadata": {}, "outputs": [], "source": [ @@ -270,7 +270,7 @@ }, { "cell_type": "markdown", - "id": "369696fa", + "id": "e47aefc6", "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": "b97730b0", + "id": "84538d49", "metadata": {}, "outputs": [], "source": [ @@ -290,7 +290,7 @@ }, { "cell_type": "markdown", - "id": "049fbd3b", + "id": "91a936ab", "metadata": {}, "source": [ "The area between two lines can be shaded using `fill_between`:" @@ -299,7 +299,7 @@ { "cell_type": "code", "execution_count": null, - "id": "672b1757", + "id": "ebb0f958", "metadata": {}, "outputs": [], "source": [ @@ -313,7 +313,7 @@ }, { "cell_type": "markdown", - "id": "e866c409", + "id": "8ae52787", "metadata": {}, "source": [ "\n", @@ -324,7 +324,7 @@ { "cell_type": "code", "execution_count": null, - "id": "42fc8081", + "id": "0fe3f185", "metadata": {}, "outputs": [], "source": [ @@ -335,12 +335,12 @@ "imslc = imdat[:,:,70]\n", "plt.imshow(imslc, cmap=plt.cm.gray)\n", "plt.colorbar()\n", - "plt.grid('off')" + "plt.axis('off')" ] }, { "cell_type": "markdown", - "id": "83fb2bb3", + "id": "dabed6ef", "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": "8aa53d09", + "id": "65e1381a", "metadata": {}, "outputs": [], "source": [ @@ -360,12 +360,12 @@ "plt.xlim(reversed(plt.xlim()))\n", "plt.ylim(reversed(plt.ylim()))\n", "plt.colorbar()\n", - "plt.grid('off')" + "plt.axis('off')" ] }, { "cell_type": "markdown", - "id": "43fce6ce", + "id": "0e20f40f", "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": "37c81436", + "id": "c5101a5b", "metadata": {}, "outputs": [], "source": [ @@ -390,7 +390,7 @@ }, { "cell_type": "markdown", - "id": "40daff02", + "id": "6c91efd8", "metadata": {}, "source": [ "By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),\n", @@ -425,7 +425,7 @@ { "cell_type": "code", "execution_count": null, - "id": "660d1559", + "id": "994a4e47", "metadata": {}, "outputs": [], "source": [ @@ -436,7 +436,7 @@ }, { "cell_type": "markdown", - "id": "2ad9cfbf", + "id": "0c244a1a", "metadata": {}, "source": [ "Note that here we explicitly create the figure and add a single sub-plot to the figure.\n", @@ -450,7 +450,7 @@ { "cell_type": "code", "execution_count": null, - "id": "7be3b246", + "id": "87b60efe", "metadata": {}, "outputs": [], "source": [ @@ -459,7 +459,7 @@ }, { "cell_type": "markdown", - "id": "7fbf6acd", + "id": "9e8785b0", "metadata": {}, "source": [ "When going through this list carefully you might have spotted that the plotted line is stored in the `lines` property.\n", @@ -469,7 +469,7 @@ { "cell_type": "code", "execution_count": null, - "id": "80481e71", + "id": "1e9372b7", "metadata": {}, "outputs": [], "source": [ @@ -478,7 +478,7 @@ }, { "cell_type": "markdown", - "id": "fa8e6fee", + "id": "afd6a54e", "metadata": {}, "source": [ "This shows us all the properties stored about this line,\n", @@ -495,7 +495,7 @@ { "cell_type": "code", "execution_count": null, - "id": "83b536d2", + "id": "5bff872f", "metadata": {}, "outputs": [], "source": [ @@ -511,7 +511,7 @@ }, { "cell_type": "markdown", - "id": "3438c4f7", + "id": "510185fb", "metadata": {}, "source": [ "For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the\n", @@ -523,7 +523,7 @@ { "cell_type": "code", "execution_count": null, - "id": "4731d436", + "id": "52ffc81d", "metadata": {}, "outputs": [], "source": [ @@ -536,7 +536,7 @@ }, { "cell_type": "markdown", - "id": "bca7abe6", + "id": "48464ab0", "metadata": {}, "source": [ "Here we use `plt.subplots`, which creates both a new figure for us and a grid of sub-plots. \n", @@ -551,7 +551,7 @@ { "cell_type": "code", "execution_count": null, - "id": "83fab131", + "id": "d047679b", "metadata": {}, "outputs": [], "source": [ @@ -565,7 +565,7 @@ }, { "cell_type": "markdown", - "id": "609cdb3f", + "id": "c8fe247b", "metadata": {}, "source": [ "Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.\n", @@ -576,7 +576,7 @@ { "cell_type": "code", "execution_count": null, - "id": "972fda35", + "id": "c82a0837", "metadata": {}, "outputs": [], "source": [ @@ -591,7 +591,7 @@ }, { "cell_type": "markdown", - "id": "18d903e1", + "id": "09b2b281", "metadata": {}, "source": [ "\n", @@ -603,7 +603,7 @@ { "cell_type": "code", "execution_count": null, - "id": "e98b00c8", + "id": "b4f4a54b", "metadata": {}, "outputs": [], "source": [ @@ -623,7 +623,7 @@ }, { "cell_type": "markdown", - "id": "0d363e0e", + "id": "37bc60de", "metadata": {}, "source": [ "\n", @@ -637,7 +637,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9553b91a", + "id": "c4b8f402", "metadata": {}, "outputs": [], "source": [ @@ -650,7 +650,7 @@ }, { "cell_type": "markdown", - "id": "79b53065", + "id": "7c6e0fc1", "metadata": {}, "source": [ "You can also set any of these properties by calling `Axes.set` directly:" @@ -659,7 +659,7 @@ { "cell_type": "code", "execution_count": null, - "id": "97643220", + "id": "ff0502fc", "metadata": {}, "outputs": [], "source": [ @@ -674,7 +674,7 @@ }, { "cell_type": "markdown", - "id": "e2fbb884", + "id": "0db1eb83", "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", @@ -685,7 +685,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5f16a656", + "id": "369c02d6", "metadata": {}, "outputs": [], "source": [ @@ -698,7 +698,7 @@ }, { "cell_type": "markdown", - "id": "f69eb693", + "id": "6095ba78", "metadata": {}, "source": [ "\n", @@ -717,7 +717,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b2d196a9", + "id": "c8f5a0dd", "metadata": {}, "outputs": [], "source": [ @@ -738,7 +738,7 @@ }, { "cell_type": "markdown", - "id": "c4c35f2a", + "id": "2dbbad8d", "metadata": {}, "source": [ "As illustrated earlier, we can get a more complete list of the things we could change about the x-axis by looking at its properties:" @@ -747,16 +747,16 @@ { "cell_type": "code", "execution_count": null, - "id": "ab2633a6", + "id": "20ca99eb", "metadata": {}, "outputs": [], "source": [ - "plt.getp(axes.get_xlabel())" + "plt.getp(axes.get_xaxis())" ] }, { "cell_type": "markdown", - "id": "440d18ce", + "id": "35fe5da3", "metadata": {}, "source": [ "\n", @@ -788,7 +788,7 @@ { "cell_type": "code", "execution_count": null, - "id": "93dbeb6e", + "id": "1620a4da", "metadata": {}, "outputs": [], "source": [ @@ -797,7 +797,7 @@ }, { "cell_type": "markdown", - "id": "d53eef2b", + "id": "b0024423", "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", @@ -808,17 +808,17 @@ { "cell_type": "code", "execution_count": null, - "id": "c16b4394", + "id": "b67ee344", "metadata": {}, "outputs": [], "source": [ "import matplotlib\n", - "matplotlib.use(\"osx\")" + "matplotlib.use(\"MacOSX\")" ] }, { "cell_type": "markdown", - "id": "96529a3c", + "id": "36ca2dfc", "metadata": {}, "source": [ "Usually, the default backend will be fine, so you will not have to set it. \n", diff --git a/applications/plotting/matplotlib.md b/applications/plotting/matplotlib.md index cb93644..1035ae2 100644 --- a/applications/plotting/matplotlib.md +++ b/applications/plotting/matplotlib.md @@ -159,7 +159,7 @@ imdat = nim.get_data().astype(float) imslc = imdat[:,:,70] plt.imshow(imslc, cmap=plt.cm.gray) plt.colorbar() -plt.grid('off') +plt.axis('off') ``` Note that matplotlib will use the **voxel data orientation**, and that @@ -173,7 +173,7 @@ plt.imshow(imslc.T, cmap=plt.cm.gray) plt.xlim(reversed(plt.xlim())) plt.ylim(reversed(plt.ylim())) plt.colorbar() -plt.grid('off') +plt.axis('off') ``` > It is easier to produce informative brain images using nilearn or fsleyes @@ -375,7 +375,7 @@ fig.tight_layout() As illustrated earlier, we can get a more complete list of the things we could change about the x-axis by looking at its properties: ``` -plt.getp(axes.get_xlabel()) +plt.getp(axes.get_xaxis()) ``` @@ -410,7 +410,7 @@ You can change backends in the IPython terminal/notebook using: In python scripts, this will give you a syntax error and you should instead use: ``` import matplotlib -matplotlib.use("osx") +matplotlib.use("MacOSX") ``` 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. \ No newline at end of file diff --git a/getting_started/06_plotting.ipynb b/getting_started/06_plotting.ipynb index dec5c15..7439d0d 100644 --- a/getting_started/06_plotting.ipynb +++ b/getting_started/06_plotting.ipynb @@ -2,6 +2,7 @@ "cells": [ { "cell_type": "markdown", + "id": "ea6b9781", "metadata": {}, "source": [ "# Plotting with python\n", @@ -35,6 +36,7 @@ { "cell_type": "code", "execution_count": null, + "id": "35ff2bd1", "metadata": {}, "outputs": [], "source": [ @@ -43,6 +45,7 @@ }, { "cell_type": "markdown", + "id": "c3d1fa16", "metadata": {}, "source": [ "This only needs to be done once in a notebook, like for standard imports.\n", @@ -60,6 +63,7 @@ { "cell_type": "code", "execution_count": null, + "id": "0963c7e2", "metadata": {}, "outputs": [], "source": [ @@ -80,6 +84,7 @@ }, { "cell_type": "markdown", + "id": "801fad5d", "metadata": {}, "source": [ "> Note that the `plt.style.use('bmh')` command is not necessary, but it\n", @@ -94,6 +99,7 @@ { "cell_type": "code", "execution_count": null, + "id": "da1d3278", "metadata": {}, "outputs": [], "source": [ @@ -106,6 +112,7 @@ }, { "cell_type": "markdown", + "id": "26173cb4", "metadata": {}, "source": [ "Use `dir()` or `help()` or the online docs to get more info on what\n", @@ -120,6 +127,7 @@ { "cell_type": "code", "execution_count": null, + "id": "7a7ef2b9", "metadata": {}, "outputs": [], "source": [ @@ -129,6 +137,7 @@ }, { "cell_type": "markdown", + "id": "3ec49cd2", "metadata": {}, "source": [ "where it also returns the number of elements in each bin, as `n`, and\n", @@ -145,6 +154,7 @@ { "cell_type": "code", "execution_count": null, + "id": "69572b88", "metadata": {}, "outputs": [], "source": [ @@ -159,6 +169,7 @@ }, { "cell_type": "markdown", + "id": "94e33c3e", "metadata": {}, "source": [ "\n", @@ -171,6 +182,7 @@ { "cell_type": "code", "execution_count": null, + "id": "1ef6ef5a", "metadata": {}, "outputs": [], "source": [ @@ -187,6 +199,7 @@ }, { "cell_type": "markdown", + "id": "69710e7b", "metadata": {}, "source": [ "> Note that in this case we use the first line return to get a handle to\n", @@ -207,6 +220,7 @@ { "cell_type": "code", "execution_count": null, + "id": "3ffabeb2", "metadata": {}, "outputs": [], "source": [ @@ -222,6 +236,7 @@ }, { "cell_type": "markdown", + "id": "2c285f4e", "metadata": {}, "source": [ "\n", @@ -233,6 +248,7 @@ { "cell_type": "code", "execution_count": null, + "id": "9bfff4b7", "metadata": {}, "outputs": [], "source": [ @@ -243,11 +259,12 @@ "imslc = imdat[:,:,70]\n", "plt.imshow(imslc, cmap=plt.cm.gray)\n", "plt.colorbar()\n", - "plt.grid('off')" + "plt.axis('off')" ] }, { "cell_type": "markdown", + "id": "bd7cd76e", "metadata": {}, "source": [ "Note that matplotlib will use the **voxel data orientation**, and that\n", @@ -259,6 +276,7 @@ { "cell_type": "code", "execution_count": null, + "id": "3623ebcc", "metadata": {}, "outputs": [], "source": [ @@ -266,11 +284,12 @@ "plt.xlim(reversed(plt.xlim()))\n", "plt.ylim(reversed(plt.ylim()))\n", "plt.colorbar()\n", - "plt.grid('off')\n" + "plt.axis('off')\n" ] }, { "cell_type": "markdown", + "id": "a39985aa", "metadata": {}, "source": [ "\n", @@ -280,6 +299,7 @@ { "cell_type": "code", "execution_count": null, + "id": "fc6a81c9", "metadata": {}, "outputs": [], "source": [ @@ -299,6 +319,7 @@ }, { "cell_type": "markdown", + "id": "ada68f3e", "metadata": {}, "source": [ "Surface renderings are many other plots are possible - see 3D examples on\n", @@ -333,14 +354,23 @@ { "cell_type": "code", "execution_count": null, + "id": "5e6f0017", "metadata": {}, "outputs": [], "source": [ "# Make up some data and do the funky plot" ] + }, + { + "cell_type": "markdown", + "id": "b517e96f", + "metadata": {}, + "source": [ + "If you want more plotting goodneess, have a look at the various tutorials available in the `applications/plottings` folder." + ] } ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/getting_started/06_plotting.md b/getting_started/06_plotting.md index ed1e58e..1def8b6 100644 --- a/getting_started/06_plotting.md +++ b/getting_started/06_plotting.md @@ -156,7 +156,7 @@ imdat = nim.get_data().astype(float) imslc = imdat[:,:,70] plt.imshow(imslc, cmap=plt.cm.gray) plt.colorbar() -plt.grid('off') +plt.axis('off') ``` Note that matplotlib will use the **voxel data orientation**, and that @@ -170,7 +170,7 @@ plt.imshow(imslc.T, cmap=plt.cm.gray) plt.xlim(reversed(plt.xlim())) plt.ylim(reversed(plt.ylim())) plt.colorbar() -plt.grid('off') +plt.axis('off') ``` -- GitLab From 427d64cdeb1107b6c48259b94ed3625ea331d0fd Mon Sep 17 00:00:00 2001 From: Michiel Cottaar Date: Wed, 28 Apr 2021 15:44:31 +0100 Subject: [PATCH 9/9] move to data_visualisation directory --- .../matplotlib.ipynb | 122 +++++++++--------- .../matplotlib.md | 0 2 files changed, 61 insertions(+), 61 deletions(-) rename applications/{plotting => data_visualisation}/matplotlib.ipynb (95%) rename applications/{plotting => data_visualisation}/matplotlib.md (100%) diff --git a/applications/plotting/matplotlib.ipynb b/applications/data_visualisation/matplotlib.ipynb similarity index 95% rename from applications/plotting/matplotlib.ipynb rename to applications/data_visualisation/matplotlib.ipynb index 921bfcf..b13b541 100644 --- a/applications/plotting/matplotlib.ipynb +++ b/applications/data_visualisation/matplotlib.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "dda775e0", + "id": "fa095385", "metadata": {}, "source": [ "# Matplotlib tutorial\n", @@ -48,7 +48,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5ccc9a73", + "id": "41578cdc", "metadata": {}, "outputs": [], "source": [ @@ -58,7 +58,7 @@ }, { "cell_type": "markdown", - "id": "ed561bcb", + "id": "1a9a5f55", "metadata": {}, "source": [ "\n", @@ -69,7 +69,7 @@ { "cell_type": "code", "execution_count": null, - "id": "80e15ee1", + "id": "2531bb20", "metadata": {}, "outputs": [], "source": [ @@ -78,7 +78,7 @@ }, { "cell_type": "markdown", - "id": "c2923739", + "id": "9ef51d5c", "metadata": {}, "source": [ "To adjust how the line is plotted, check the documentation:" @@ -87,7 +87,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0ce4a966", + "id": "9a768ab3", "metadata": {}, "outputs": [], "source": [ @@ -96,7 +96,7 @@ }, { "cell_type": "markdown", - "id": "e7263d90", + "id": "d2e6a4d1", "metadata": {}, "source": [ "As you can see there are a lot of options.\n", @@ -109,7 +109,7 @@ { "cell_type": "code", "execution_count": null, - "id": "dfbbb093", + "id": "85ed5f73", "metadata": {}, "outputs": [], "source": [ @@ -123,7 +123,7 @@ }, { "cell_type": "markdown", - "id": "c5cf861d", + "id": "a359e01a", "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": "9446bd5b", + "id": "0e69e842", "metadata": {}, "outputs": [], "source": [ @@ -145,7 +145,7 @@ }, { "cell_type": "markdown", - "id": "f17ba1d2", + "id": "891a9f9e", "metadata": {}, "source": [ "\n", @@ -156,7 +156,7 @@ { "cell_type": "code", "execution_count": null, - "id": "31c06d59", + "id": "8cb13b7e", "metadata": {}, "outputs": [], "source": [ @@ -168,7 +168,7 @@ }, { "cell_type": "markdown", - "id": "777734ae", + "id": "df311f5c", "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": "1fd95cae", + "id": "f9bb4e76", "metadata": {}, "outputs": [], "source": [ @@ -190,7 +190,7 @@ }, { "cell_type": "markdown", - "id": "72a015c6", + "id": "141bf7e8", "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": "0c410bcd", + "id": "951bd53e", "metadata": {}, "outputs": [], "source": [ @@ -222,7 +222,7 @@ }, { "cell_type": "markdown", - "id": "75c96456", + "id": "2ae38282", "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": "00caf192", + "id": "3f440fd0", "metadata": {}, "outputs": [], "source": [ @@ -249,7 +249,7 @@ }, { "cell_type": "markdown", - "id": "dd9fb30f", + "id": "1405cf82", "metadata": {}, "source": [ "\n", @@ -260,7 +260,7 @@ { "cell_type": "code", "execution_count": null, - "id": "bb53b679", + "id": "c0f12a0d", "metadata": {}, "outputs": [], "source": [ @@ -270,7 +270,7 @@ }, { "cell_type": "markdown", - "id": "e47aefc6", + "id": "71d7bc82", "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": "84538d49", + "id": "e337ced8", "metadata": {}, "outputs": [], "source": [ @@ -290,7 +290,7 @@ }, { "cell_type": "markdown", - "id": "91a936ab", + "id": "12c4eee6", "metadata": {}, "source": [ "The area between two lines can be shaded using `fill_between`:" @@ -299,7 +299,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ebb0f958", + "id": "54c6b838", "metadata": {}, "outputs": [], "source": [ @@ -313,7 +313,7 @@ }, { "cell_type": "markdown", - "id": "8ae52787", + "id": "3a1d3815", "metadata": {}, "source": [ "\n", @@ -324,7 +324,7 @@ { "cell_type": "code", "execution_count": null, - "id": "0fe3f185", + "id": "ed051029", "metadata": {}, "outputs": [], "source": [ @@ -340,7 +340,7 @@ }, { "cell_type": "markdown", - "id": "dabed6ef", + "id": "156b0628", "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": "65e1381a", + "id": "a65cf0d6", "metadata": {}, "outputs": [], "source": [ @@ -365,7 +365,7 @@ }, { "cell_type": "markdown", - "id": "0e20f40f", + "id": "7c8a01a8", "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": "c5101a5b", + "id": "3f9f4fad", "metadata": {}, "outputs": [], "source": [ @@ -390,7 +390,7 @@ }, { "cell_type": "markdown", - "id": "6c91efd8", + "id": "d2fb44b4", "metadata": {}, "source": [ "By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),\n", @@ -425,7 +425,7 @@ { "cell_type": "code", "execution_count": null, - "id": "994a4e47", + "id": "43229971", "metadata": {}, "outputs": [], "source": [ @@ -436,7 +436,7 @@ }, { "cell_type": "markdown", - "id": "0c244a1a", + "id": "8d4bee33", "metadata": {}, "source": [ "Note that here we explicitly create the figure and add a single sub-plot to the figure.\n", @@ -450,7 +450,7 @@ { "cell_type": "code", "execution_count": null, - "id": "87b60efe", + "id": "2cc5123a", "metadata": {}, "outputs": [], "source": [ @@ -459,7 +459,7 @@ }, { "cell_type": "markdown", - "id": "9e8785b0", + "id": "37251f4a", "metadata": {}, "source": [ "When going through this list carefully you might have spotted that the plotted line is stored in the `lines` property.\n", @@ -469,7 +469,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1e9372b7", + "id": "db290a0a", "metadata": {}, "outputs": [], "source": [ @@ -478,7 +478,7 @@ }, { "cell_type": "markdown", - "id": "afd6a54e", + "id": "ae053e0c", "metadata": {}, "source": [ "This shows us all the properties stored about this line,\n", @@ -495,7 +495,7 @@ { "cell_type": "code", "execution_count": null, - "id": "5bff872f", + "id": "8bd710d5", "metadata": {}, "outputs": [], "source": [ @@ -511,7 +511,7 @@ }, { "cell_type": "markdown", - "id": "510185fb", + "id": "28b82718", "metadata": {}, "source": [ "For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the\n", @@ -523,7 +523,7 @@ { "cell_type": "code", "execution_count": null, - "id": "52ffc81d", + "id": "89a20086", "metadata": {}, "outputs": [], "source": [ @@ -536,7 +536,7 @@ }, { "cell_type": "markdown", - "id": "48464ab0", + "id": "852c2d46", "metadata": {}, "source": [ "Here we use `plt.subplots`, which creates both a new figure for us and a grid of sub-plots. \n", @@ -551,7 +551,7 @@ { "cell_type": "code", "execution_count": null, - "id": "d047679b", + "id": "5c14ec50", "metadata": {}, "outputs": [], "source": [ @@ -565,7 +565,7 @@ }, { "cell_type": "markdown", - "id": "c8fe247b", + "id": "338c7239", "metadata": {}, "source": [ "Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.\n", @@ -576,7 +576,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c82a0837", + "id": "5df7361f", "metadata": {}, "outputs": [], "source": [ @@ -591,7 +591,7 @@ }, { "cell_type": "markdown", - "id": "09b2b281", + "id": "ff58c930", "metadata": {}, "source": [ "\n", @@ -603,7 +603,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b4f4a54b", + "id": "c1651d0c", "metadata": {}, "outputs": [], "source": [ @@ -623,7 +623,7 @@ }, { "cell_type": "markdown", - "id": "37bc60de", + "id": "5676c42d", "metadata": {}, "source": [ "\n", @@ -637,7 +637,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c4b8f402", + "id": "b6841514", "metadata": {}, "outputs": [], "source": [ @@ -650,7 +650,7 @@ }, { "cell_type": "markdown", - "id": "7c6e0fc1", + "id": "c27500eb", "metadata": {}, "source": [ "You can also set any of these properties by calling `Axes.set` directly:" @@ -659,7 +659,7 @@ { "cell_type": "code", "execution_count": null, - "id": "ff0502fc", + "id": "4aa8461b", "metadata": {}, "outputs": [], "source": [ @@ -674,7 +674,7 @@ }, { "cell_type": "markdown", - "id": "0db1eb83", + "id": "e69e0f4b", "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", @@ -685,7 +685,7 @@ { "cell_type": "code", "execution_count": null, - "id": "369c02d6", + "id": "d9958b2e", "metadata": {}, "outputs": [], "source": [ @@ -698,7 +698,7 @@ }, { "cell_type": "markdown", - "id": "6095ba78", + "id": "111da8e1", "metadata": {}, "source": [ "\n", @@ -717,7 +717,7 @@ { "cell_type": "code", "execution_count": null, - "id": "c8f5a0dd", + "id": "4e402140", "metadata": {}, "outputs": [], "source": [ @@ -738,7 +738,7 @@ }, { "cell_type": "markdown", - "id": "2dbbad8d", + "id": "9bd34f1c", "metadata": {}, "source": [ "As illustrated earlier, we can get a more complete list of the things we could change about the x-axis by looking at its properties:" @@ -747,7 +747,7 @@ { "cell_type": "code", "execution_count": null, - "id": "20ca99eb", + "id": "db2b0e6e", "metadata": {}, "outputs": [], "source": [ @@ -756,7 +756,7 @@ }, { "cell_type": "markdown", - "id": "35fe5da3", + "id": "48b79b04", "metadata": {}, "source": [ "\n", @@ -788,7 +788,7 @@ { "cell_type": "code", "execution_count": null, - "id": "1620a4da", + "id": "e36ee821", "metadata": {}, "outputs": [], "source": [ @@ -797,7 +797,7 @@ }, { "cell_type": "markdown", - "id": "b0024423", + "id": "68b0aac8", "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", @@ -808,7 +808,7 @@ { "cell_type": "code", "execution_count": null, - "id": "b67ee344", + "id": "b81eb924", "metadata": {}, "outputs": [], "source": [ @@ -818,7 +818,7 @@ }, { "cell_type": "markdown", - "id": "36ca2dfc", + "id": "14663014", "metadata": {}, "source": [ "Usually, the default backend will be fine, so you will not have to set it. \n", diff --git a/applications/plotting/matplotlib.md b/applications/data_visualisation/matplotlib.md similarity index 100% rename from applications/plotting/matplotlib.md rename to applications/data_visualisation/matplotlib.md -- GitLab