matplotlib.ipynb 27.3 KB
Newer Older
Michiel Cottaar's avatar
Michiel Cottaar committed
1
2
3
4
{
 "cells": [
  {
   "cell_type": "markdown",
5
   "id": "dda775e0",
Michiel Cottaar's avatar
Michiel Cottaar committed
6
7
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
8
    "# Matplotlib tutorial\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    "\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",
Michiel Cottaar's avatar
Michiel Cottaar committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    "- [Basic plotting commands](#basic-plotting-commands)\n",
    "  - [Line plots](#line)\n",
    "  - [Scatter plots](#scatter)\n",
    "  - [Histograms and bar plots](#histograms)\n",
    "  - [Adding error bars](#error)\n",
    "  - [Shading regions](#shade)\n",
    "  - [Displaying images](#image)\n",
    "  - [Adding lines, arrows, text](#annotations)\n",
    "- [Using the object-oriented interface](#OO)\n",
    "- [Multiple plots (i.e., subplots)](#subplots)\n",
    "  - [Adjusting plot layouts](#layout)\n",
    "  - [Advanced grid configurations (GridSpec)](#grid-spec)\n",
    "- [Styling your plot](#styling)\n",
    "  - [Setting title and labels](#labels)\n",
    "  - [Editing the x- and y-axis](#axis)\n",
    "- [FAQ](#faq)\n",
    "  - [Why am I getting two images?](#double-image)\n",
    "  - [I produced a plot in my python script, but it does not show up](#show)\n",
    "  - [Changing where the image appears: backends](#backends)\n",
    "\n",
    "<a class=\"anchor\" id=\"basic-plotting-commands\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
44
45
46
47
48
49
50
    "## Basic plotting commands\n",
    "Let's start with the basic imports:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
51
   "id": "5ccc9a73",
Michiel Cottaar's avatar
Michiel Cottaar committed
52
53
54
55
56
57
58
59
60
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
61
   "id": "ed561bcb",
Michiel Cottaar's avatar
Michiel Cottaar committed
62
63
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
64
    "<a class=\"anchor\" id=\"line\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
65
66
67
68
69
70
71
    "### Line plots\n",
    "A basic lineplot can be made just by calling `plt.plot`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
72
   "id": "80e15ee1",
Michiel Cottaar's avatar
Michiel Cottaar committed
73
74
75
76
77
78
79
80
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot([1, 2, 3], [1.3, 4.2, 3.1])"
   ]
  },
  {
   "cell_type": "markdown",
81
   "id": "c2923739",
Michiel Cottaar's avatar
Michiel Cottaar committed
82
83
84
85
86
87
88
89
   "metadata": {},
   "source": [
    "To adjust how the line is plotted, check the documentation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
90
   "id": "0ce4a966",
Michiel Cottaar's avatar
Michiel Cottaar committed
91
92
93
94
95
96
97
98
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot?"
   ]
  },
  {
   "cell_type": "markdown",
99
   "id": "e7263d90",
Michiel Cottaar's avatar
Michiel Cottaar committed
100
101
102
103
104
105
106
107
108
109
110
111
   "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,
112
   "id": "dfbbb093",
Michiel Cottaar's avatar
Michiel Cottaar committed
113
114
115
116
117
118
119
120
121
122
123
124
125
   "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",
126
   "id": "c5cf861d",
Michiel Cottaar's avatar
Michiel Cottaar committed
127
128
129
130
131
132
133
134
   "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,
135
   "id": "9446bd5b",
Michiel Cottaar's avatar
Michiel Cottaar committed
136
137
138
139
140
141
142
143
144
145
146
147
   "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",
148
   "id": "f17ba1d2",
Michiel Cottaar's avatar
Michiel Cottaar committed
149
150
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
151
    "<a class=\"anchor\" id=\"scatter\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
152
153
154
155
156
157
158
    "### 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,
159
   "id": "31c06d59",
Michiel Cottaar's avatar
Michiel Cottaar committed
160
161
162
163
164
165
166
167
168
169
170
   "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",
171
   "id": "777734ae",
Michiel Cottaar's avatar
Michiel Cottaar committed
172
173
174
   "metadata": {},
   "source": [
    "The third argument is the variable determining the size, while the fourth argument is the variable setting the color.\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
175
    "<a class=\"anchor\" id=\"histograms\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
176
177
178
179
180
181
182
    "### Histograms and bar plots\n",
    "For a simple histogram you can do this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
183
   "id": "1fd95cae",
Michiel Cottaar's avatar
Michiel Cottaar committed
184
185
186
187
188
189
190
191
192
   "metadata": {},
   "outputs": [],
   "source": [
    "r = np.random.rand(1000)\n",
    "n,bins,_ = plt.hist((r-0.5)**2, bins=30)"
   ]
  },
  {
   "cell_type": "markdown",
193
   "id": "72a015c6",
Michiel Cottaar's avatar
Michiel Cottaar committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
   "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,
210
   "id": "0c410bcd",
Michiel Cottaar's avatar
Michiel Cottaar committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
   "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",
225
   "id": "75c96456",
Michiel Cottaar's avatar
Michiel Cottaar committed
226
227
228
229
   "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",
Michiel Cottaar's avatar
Michiel Cottaar committed
230
    "<a class=\"anchor\" id=\"error\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
231
232
233
234
235
236
237
238
    "### 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,
239
   "id": "00caf192",
Michiel Cottaar's avatar
Michiel Cottaar committed
240
241
242
243
244
245
246
247
248
249
250
251
   "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",
252
   "id": "dd9fb30f",
Michiel Cottaar's avatar
Michiel Cottaar committed
253
254
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
255
    "<a class=\"anchor\" id=\"shade\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
256
257
258
259
260
261
262
    "### Shading regions\n",
    "An area below a plot can be shaded using `plt.fill`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
263
   "id": "bb53b679",
Michiel Cottaar's avatar
Michiel Cottaar committed
264
265
266
267
268
269
270
271
272
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(0, 2, 100)\n",
    "plt.fill(x, np.sin(x * np.pi))"
   ]
  },
  {
   "cell_type": "markdown",
273
   "id": "e47aefc6",
Michiel Cottaar's avatar
Michiel Cottaar committed
274
275
276
277
278
279
280
281
   "metadata": {},
   "source": [
    "This can be nicely combined with a polar projection, to create 2D orientation distribution functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
282
   "id": "84538d49",
Michiel Cottaar's avatar
Michiel Cottaar committed
283
284
285
286
287
288
289
290
291
292
   "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",
293
   "id": "91a936ab",
Michiel Cottaar's avatar
Michiel Cottaar committed
294
295
296
297
298
299
300
301
   "metadata": {},
   "source": [
    "The area between two lines can be shaded using `fill_between`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
302
   "id": "ebb0f958",
Michiel Cottaar's avatar
Michiel Cottaar committed
303
304
305
306
307
308
309
310
311
312
313
314
315
   "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",
316
   "id": "8ae52787",
Michiel Cottaar's avatar
Michiel Cottaar committed
317
318
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
319
    "<a class=\"anchor\" id=\"image\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
320
321
322
323
324
325
326
    "### 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,
327
   "id": "0fe3f185",
Michiel Cottaar's avatar
Michiel Cottaar committed
328
329
330
331
332
333
334
335
336
337
   "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",
338
    "plt.axis('off')"
Michiel Cottaar's avatar
Michiel Cottaar committed
339
340
341
342
   ]
  },
  {
   "cell_type": "markdown",
343
   "id": "dabed6ef",
Michiel Cottaar's avatar
Michiel Cottaar committed
344
345
346
347
348
349
350
351
352
353
354
   "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,
355
   "id": "65e1381a",
Michiel Cottaar's avatar
Michiel Cottaar committed
356
357
358
359
360
361
362
   "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",
363
    "plt.axis('off')"
Michiel Cottaar's avatar
Michiel Cottaar committed
364
365
366
367
   ]
  },
  {
   "cell_type": "markdown",
368
   "id": "0e20f40f",
Michiel Cottaar's avatar
Michiel Cottaar committed
369
370
371
   "metadata": {},
   "source": [
    "> It is easier to produce informative brain images using nilearn or fsleyes\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
372
    "<a class=\"anchor\" id=\"annotations\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
373
374
375
376
377
378
379
    "### Adding lines, arrows, and text\n",
    "Adding horizontal/vertical lines, arrows, and text:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
380
   "id": "c5101a5b",
Michiel Cottaar's avatar
Michiel Cottaar committed
381
382
383
384
385
386
387
388
389
390
391
392
   "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",
393
   "id": "6c91efd8",
Michiel Cottaar's avatar
Michiel Cottaar committed
394
395
396
397
398
399
400
401
   "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",
Michiel Cottaar's avatar
Michiel Cottaar committed
402
    "<a class=\"anchor\" id=\"OO\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
403
404
    "## Using the object-oriented interface\n",
    "In the examples above we simply added multiple lines/points/bars/images \n",
405
    "(collectively called [artists](https://matplotlib.org/stable/tutorials/intermediate/artists.html) in matplotlib) to a single plot.\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
406
    "To prettify this plots, we first need to know what all the features are called:\n",
407
408
409
410
    "\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",
Michiel Cottaar's avatar
Michiel Cottaar committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
    "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,
428
   "id": "994a4e47",
Michiel Cottaar's avatar
Michiel Cottaar committed
429
430
431
432
433
434
435
436
437
438
   "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",
439
   "id": "0c244a1a",
Michiel Cottaar's avatar
Michiel Cottaar committed
440
441
442
443
444
445
   "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",
Michiel Cottaar's avatar
Michiel Cottaar committed
446
    "\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
447
448
449
450
451
452
    "`plt.getp` gives a helpful summary of the properties of a matplotlib object (and what you might change):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
453
   "id": "87b60efe",
Michiel Cottaar's avatar
Michiel Cottaar committed
454
455
456
457
458
459
460
461
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.getp(ax)"
   ]
  },
  {
   "cell_type": "markdown",
462
   "id": "9e8785b0",
Michiel Cottaar's avatar
Michiel Cottaar committed
463
464
465
466
467
468
469
470
471
   "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,
472
   "id": "1e9372b7",
Michiel Cottaar's avatar
Michiel Cottaar committed
473
474
475
476
477
478
479
480
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.getp(ax.lines[0])"
   ]
  },
  {
   "cell_type": "markdown",
481
   "id": "afd6a54e",
Michiel Cottaar's avatar
Michiel Cottaar committed
482
483
484
485
486
487
488
   "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",
Michiel Cottaar's avatar
Michiel Cottaar committed
489
    "<a class=\"anchor\" id=\"subplots\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
490
491
492
493
494
495
496
497
    "## 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,
498
   "id": "5bff872f",
Michiel Cottaar's avatar
Michiel Cottaar committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
   "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",
514
   "id": "510185fb",
Michiel Cottaar's avatar
Michiel Cottaar committed
515
516
517
518
519
520
521
522
523
524
525
   "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,
526
   "id": "52ffc81d",
Michiel Cottaar's avatar
Michiel Cottaar committed
527
528
529
530
531
532
533
534
535
536
537
538
   "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",
539
   "id": "48464ab0",
Michiel Cottaar's avatar
Michiel Cottaar committed
540
541
542
543
544
545
   "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",
Michiel Cottaar's avatar
Michiel Cottaar committed
546
    "<a class=\"anchor\" id=\"layout\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
547
548
549
550
551
552
553
    "### 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,
554
   "id": "d047679b",
Michiel Cottaar's avatar
Michiel Cottaar committed
555
556
557
558
559
560
561
562
563
564
565
566
567
   "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",
568
   "id": "c8fe247b",
Michiel Cottaar's avatar
Michiel Cottaar committed
569
570
571
572
573
574
575
576
577
578
   "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,
579
   "id": "c82a0837",
Michiel Cottaar's avatar
Michiel Cottaar committed
580
581
582
583
584
585
586
587
588
589
590
591
592
593
   "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",
594
   "id": "09b2b281",
Michiel Cottaar's avatar
Michiel Cottaar committed
595
596
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
597
    "<a class=\"anchor\" id=\"grid-spec\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
598
599
600
601
602
603
604
605
    "### 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,
606
   "id": "b4f4a54b",
Michiel Cottaar's avatar
Michiel Cottaar committed
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
   "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",
626
   "id": "37bc60de",
Michiel Cottaar's avatar
Michiel Cottaar committed
627
628
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
629
    "<a class=\"anchor\" id=\"styling\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
630
    "## Styling your plot\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
631
    "<a class=\"anchor\" id=\"labels\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
632
633
634
635
636
637
638
639
    "### 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,
640
   "id": "c4b8f402",
Michiel Cottaar's avatar
Michiel Cottaar committed
641
642
643
644
645
646
647
648
649
650
651
652
   "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",
653
   "id": "7c6e0fc1",
Michiel Cottaar's avatar
Michiel Cottaar committed
654
655
656
657
658
659
660
661
   "metadata": {},
   "source": [
    "You can also set any of these properties by calling `Axes.set` directly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
662
   "id": "ff0502fc",
Michiel Cottaar's avatar
Michiel Cottaar committed
663
664
665
666
667
668
669
670
671
672
673
674
675
676
   "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",
677
   "id": "0db1eb83",
Michiel Cottaar's avatar
Michiel Cottaar committed
678
679
680
681
   "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",
Michiel Cottaar's avatar
Michiel Cottaar committed
682
    "You can edit the font of the text when setting the label or after the fact using the object-oriented interface:"
Michiel Cottaar's avatar
Michiel Cottaar committed
683
684
685
686
687
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
688
   "id": "369c02d6",
Michiel Cottaar's avatar
Michiel Cottaar committed
689
690
691
692
693
694
   "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",
Michiel Cottaar's avatar
Michiel Cottaar committed
695
696
    "axes.set_ylabel(\"ylabel\")\n",
    "axes.get_yaxis().get_label().set_fontsize('larger')"
Michiel Cottaar's avatar
Michiel Cottaar committed
697
698
699
700
   ]
  },
  {
   "cell_type": "markdown",
701
   "id": "6095ba78",
Michiel Cottaar's avatar
Michiel Cottaar committed
702
703
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
704
    "<a class=\"anchor\" id=\"axis\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
    "### 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,
720
   "id": "c8f5a0dd",
Michiel Cottaar's avatar
Michiel Cottaar committed
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
   "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",
741
   "id": "2dbbad8d",
Michiel Cottaar's avatar
Michiel Cottaar committed
742
743
744
745
746
747
748
749
   "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,
750
   "id": "20ca99eb",
Michiel Cottaar's avatar
Michiel Cottaar committed
751
752
753
   "metadata": {},
   "outputs": [],
   "source": [
754
    "plt.getp(axes.get_xaxis())"
Michiel Cottaar's avatar
Michiel Cottaar committed
755
756
757
758
   ]
  },
  {
   "cell_type": "markdown",
759
   "id": "35fe5da3",
Michiel Cottaar's avatar
Michiel Cottaar committed
760
761
   "metadata": {},
   "source": [
Michiel Cottaar's avatar
Michiel Cottaar committed
762
    "<a class=\"anchor\" id=\"faq\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
763
    "## FAQ\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
764
    "<a class=\"anchor\" id=\"double-image\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
765
    "### Why am I getting two images?\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
766
767
768
769
770
771
    "Any figure you produce in the notebook will be shown by default once a cell successfully finishes (i.e., without error).\n",
    "If the code in a notebook cell crashes after creating the figure, this figure will still be in memory.\n",
    "It will be shown after another cell successfully finishes.\n",
    "You can remove this additional plot simply by rerunning the cell, after which you should only see the plot produced by the cell in question.\n",
    "\n",
    "<a class=\"anchor\" id=\"show\"></a>\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
772
773
774
775
    "### 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",
Michiel Cottaar's avatar
Michiel Cottaar committed
776
777
    "<a class=\"anchor\" id=\"backends\"></a>\n",
    "### Changing where the image appears: backends\n",
Michiel Cottaar's avatar
Michiel Cottaar committed
778
779
780
781
782
783
784
785
786
787
788
789
790
    "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,
791
   "id": "1620a4da",
Michiel Cottaar's avatar
Michiel Cottaar committed
792
793
794
795
796
797
798
799
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib nbagg"
   ]
  },
  {
   "cell_type": "markdown",
800
   "id": "b0024423",
Michiel Cottaar's avatar
Michiel Cottaar committed
801
802
803
804
805
806
807
808
809
810
   "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,
811
   "id": "b67ee344",
Michiel Cottaar's avatar
Michiel Cottaar committed
812
813
814
815
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib\n",
816
    "matplotlib.use(\"MacOSX\")"
Michiel Cottaar's avatar
Michiel Cottaar committed
817
818
819
820
   ]
  },
  {
   "cell_type": "markdown",
821
   "id": "36ca2dfc",
Michiel Cottaar's avatar
Michiel Cottaar committed
822
823
824
825
826
827
828
   "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."
   ]
  }
 ],
Michiel Cottaar's avatar
Michiel Cottaar committed
829
 "metadata": {},
Michiel Cottaar's avatar
Michiel Cottaar committed
830
831
832
 "nbformat": 4,
 "nbformat_minor": 5
}