matplotlib.ipynb 23.4 KB
Newer Older
Michiel Cottaar's avatar
Michiel Cottaar committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
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
}