seaborn.ipynb 16 KB
Newer Older
Mo Shahdloo's avatar
Mo Shahdloo 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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "caring-plate",
   "metadata": {},
   "source": [
    "# Tabular data visualisation using Seaborn\n",
    "---\n",
    "When it comes to tabular data, one of the best libraries to choose is `Pandas` (for an intro to `Pandas` see [this tutorial](https://git.fmrib.ox.ac.uk/fsl/win-pytreat/-/blob/fsleyes_branch/applications/pandas/pandas.ipynb)). \n",
    "`Seaborn` is a visualisation library built on top of `matplotlib` and provides a convenient user interface to produce various types of plots. \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "equipped-minnesota",
   "metadata": {},
   "source": [
    "## Contents\n",
    "---\n",
    "* [Relative distributions (and basic figure aesthetics)](#scatter)\n",
    "    * [Linear regression](#linear)\n",
    "* [Data aggregation and uncertainty bounds](#line)\n",
    "* [Marginal plots](#marginals)\n",
    "\n",
    "This tutorial relies heavily on the materials provided in the [`seaborn` documentation](https://seaborn.pydata.org/examples/index.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "suspected-worthy",
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "sns.set_theme()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "champion-answer",
   "metadata": {},
   "source": [
    "## Plotting relative distributions\n",
    "---\n",
    "<a id='scatter'></a>\n",
    "Seaborn library provides a couple of `pandas` datsets to explore various plot types. The one we load below is about penguins 🐧  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "pressed-individual",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the penguins dataset\n",
    "penguins = sns.load_dataset(\"penguins\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "elder-corner",
   "metadata": {},
   "outputs": [],
   "source": [
    "penguins"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "opposite-encounter",
   "metadata": {},
   "source": [
    "Now let's see how the distribution of bill length vs depth look like. To do this, we have to pass these parameter names to the `x` and `y` axes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "placed-egyptian",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "intensive-citizenship",
   "metadata": {},
   "source": [
    "---\n",
    "Let's open a large paranthesis here and explore some of the parameters that control figure aesthetics. We will later return to explore different plot types.\n",
    "\n",
    "Seaborn comes with a couple of predefined themes; `darkgrid`, `whitegrid`, `dark`, `white`, `ticks`. \n",
    "Let's make the figure above a bit fancier"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "herbal-combine",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.set_style('whitegrid') # which means white background, and grids on"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "shaped-clinton",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sealed-egyptian",
   "metadata": {},
   "source": [
    "other styles look like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "regular-oriental",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "for style in ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks']:\n",
    "    sns.set_style(style)\n",
    "    g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eleven-librarian",
   "metadata": {},
   "source": [
    "To remove the top and right axis spines in the `white`, `whitegrid`, and `tick` themes you can call the `despine()` function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cosmetic-event",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.set_style('white')\n",
    "g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm')\n",
    "sns.despine()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "laughing-islam",
   "metadata": {},
   "source": [
    "Axes labels can also be set to something human-readable, and making the markers larger makes the figure nicer..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "seven-allergy",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', s=80)\n",
    "g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')\n",
    "sns.despine()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fuzzy-welsh",
   "metadata": {},
   "source": [
    "paranthesis closed.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "architectural-corruption",
   "metadata": {},
   "source": [
    "It seems that there are separate clusters in the data. A reasonable guess could be that the clusters correspond to different penguin species. We can color each dot based on a categorical variable (e.g., species) using the `hue` parameter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "designed-angle",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.scatterplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', hue='species', s=80)\n",
    "g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')\n",
    "sns.despine()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fourth-southwest",
   "metadata": {},
   "source": [
    "The guess was correct!\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "parental-dispatch",
   "metadata": {},
   "source": [
    "### Linear regression\n",
    "<a id='scatter'></a>\n",
    "There also seems to be a linear dependece between the two parameters, in each species. A linear fit to the data can be easily plotted by using `lmplot` which is a convenient shortcut to `scatterplot` with extra features for linear regression."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "protecting-oracle",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', \n",
    "               hue='species', \n",
    "               scatter_kws={\"s\": 60})\n",
    "g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)', title='Snoot depth vs length')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "brave-equilibrium",
   "metadata": {},
   "source": [
    "Note that since `lmplot` is derived from `scatterplot` any extra arguments used by `scatterplot` should be passed via `scatter_kws` parameter."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "simple-tradition",
   "metadata": {},
   "source": [
    "Alternatively, we could plot the data for each species in a separate column by setting `col` "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "robust-organizer",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', \n",
    "               hue='species',\n",
    "               col='species',\n",
    "               scatter_kws={\"s\": 60})\n",
    "g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)')\n",
    "g.fig.suptitle('Snoot depth vs length', y=1.05)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "prospective-mason",
   "metadata": {},
   "source": [
    "The confidence bounds shown above are calculated based on standard deviation by default. Alternatively confidence interval can be used by specifying the confidence interval percentage"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bored-roulette",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.lmplot(data=penguins, x='bill_length_mm', y='bill_depth_mm', \n",
    "               hue='species',\n",
    "               col='species', \n",
    "               ci=80,\n",
    "               scatter_kws={\"s\": 60})\n",
    "g.set(xlabel='Snoot length (mm)', ylabel='Snoot depth (mm)')\n",
    "g.fig.suptitle('Snoot depth vs length -- 80% CI', y=1.05)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "employed-twenty",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Data aggregation and uncertainty bounds\n",
    "<a id='line'></a>\n",
    "\n",
    "In some datasets, repetitive measurements for example, there might be multiple values from one variable corresponding to each instance from the other variable. To explore an instance of such data, lets load the `fmri` dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "south-entrance",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.set_style('ticks')\n",
    "fmri = sns.load_dataset(\"fmri\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "interracial-hello",
   "metadata": {},
   "outputs": [],
   "source": [
    "fmri"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "exclusive-yahoo",
   "metadata": {},
   "source": [
    "Lets visualise the signal values across time..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "choice-isaac",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.scatterplot(x=\"timepoint\", y=\"signal\", data=fmri)\n",
    "sns.despine()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "interesting-possession",
   "metadata": {},
   "source": [
    "To plot the mean signal versus time we can use the `relplot` "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "infrared-remainder",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, ci=None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "digital-sheriff",
   "metadata": {},
   "source": [
    "By default, mean of the signal at each `x` instance is plotted. But any arbitrary function could also be used to aggregate the data. For instance, we could use the `median` function from `numpy` package to calculate the value corresponding to each timepoint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "interesting-pizza",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, ci=None, estimator=np.median)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "medium-editing",
   "metadata": {},
   "source": [
    "Overlaying the uncertainty bounds is easily achievable by specifying the confidence interval percentage."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "demographic-video",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, ci=95, estimator=np.median)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "deluxe-hacker",
   "metadata": {},
   "source": [
    " Standard deviation could also be used instead"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "touched-technical",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, ci='sd', estimator=np.median)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fantastic-ghost",
   "metadata": {},
   "source": [
    "Similar to any other plot type in `seaborn`, data with different semantics can be separately plotted by assigning them to `hue`, `col`, or `style` parameters. Let's separately plot the data for the _parietal_ and _frontal_ regions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "better-imperial",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, hue='region')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "silent-messenger",
   "metadata": {},
   "source": [
    "or we could separate them even more detailed, based on the event type; _cue_ or _stimulus_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "regional-exhaust",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, hue='region', style='event')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "incorporated-blackjack",
   "metadata": {},
   "source": [
    "we can also plot each event in a separate subplot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "spectacular-stranger",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.relplot(x=\"timepoint\", y=\"signal\", kind=\"line\", data=fmri, hue='region', col='event')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "seeing-wages",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Marginal distributions\n",
    "<a id='marginals'></a>\n",
    "\n",
    "Let's load a larger dataset; some measurements on planets 🪐 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "incomplete-county",
   "metadata": {},
   "outputs": [],
   "source": [
    "planets = sns.load_dataset(\"planets\")\n",
    "planets = planets.dropna(subset=['mass', 'distance']) # remove NaN entries\n",
    "sns.set_style('ticks')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "abandoned-frequency",
   "metadata": {},
   "outputs": [],
   "source": [
    "planets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "czech-terminology",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "g = sns.scatterplot(data=planets, x=\"distance\", y=\"orbital_period\")\n",
    "sns.despine()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dominant-doctor",
   "metadata": {},
   "source": [
    "It seems that the data could be better delineated in log scale..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "reported-front",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = sns.scatterplot(data=planets, x=\"distance\", y=\"orbital_period\")\n",
    "g.set(yscale=\"log\", xscale=\"log\")\n",
    "sns.despine()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "living-nightlife",
   "metadata": {},
   "source": [
    "Seaborn can also plot the marginal distributions, cool!\n",
    "To do this, you should first create a `JointGrid` object that consists of a _joint_ axis and two _marginal_ axes, containing the joint distribution and the two marginal distributions. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "realistic-batman",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# define the JointGrid, and the data corresponding to each axis\n",
    "g = sns.JointGrid(data=planets, x=\"distance\", y=\"orbital_period\", marginal_ticks=True)\n",
    "\n",
    "# the distance axis should be log-scaled!\n",
    "g.ax_joint.set(yscale=\"log\", xscale=\"log\")\n",
    "\n",
    "# plot the joint scatter plot in the joint axis\n",
    "# Heavier planets are marked with larger dots, and `sizes` controls the range of marker sizes\n",
    "g.plot_joint(sns.scatterplot, size=planets.mass, sizes=(10, 200))\n",
    "\n",
    "# plot the joint histograms, overlayed with kernel density estimates\n",
    "g.plot_marginals(sns.histplot, kde=True)"
   ]
  }
 ],
 "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.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}