forked from BCCHR-trainee-omics-group/StudyGroup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintro-to-gglot2.Rmd
718 lines (522 loc) · 16.6 KB
/
intro-to-gglot2.Rmd
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
---
title: "Introduction to ggplot2"
subtitle: "download @ bit.ly/2ZOShd4"
author: "Victor Yuan"
date: "2020-07-09"
output:
xaringan::moon_reader:
css: ["default", "middlebury-fonts", "custom1.css"]
lib_dir: libs
nature:
ratio: 16:9
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE}
hook_source <- knitr::knit_hooks$get('source')
knitr::knit_hooks$set(source = function(x, options) {
x <- stringr::str_replace(x, "^[[:blank:]]?([^*].+?)[[:blank:]]*#<<[[:blank:]]*$", "*\\1")
hook_source(x, options)
})
knitr::opts_chunk$set(out.width="100%", out.height="100%")
ggplot2::theme_set(ggplot2::theme_gray(base_size=16))
```
# Set up
Install these packages
```{r eval = FALSE}
install.packages(tidyverse)
```
Load libraries
```{r}
library(tidyverse)
```
---
# Load gene expression / methylation data
```{r, message = FALSE}
geo_data <- read_csv('https://raw.githubusercontent.com/wvictor14/TOG/master/data/GSE98224.csv')
geo_data
```
---
layout: false
class: inverse center middle text-white
# 3 essential components
## to every ggplot2 graph
### **Data**, **Geom**etry, **Aes**thetics
---
First step of every ggplot2 call is to *declare* the data.
.pull-left[
```{r our-first-plot-1, eval=FALSE}
ggplot(data = geo_data) #<<
```
]
.pull-right[
```{r our-first-plot-1-out, ref.label="our-first-plot-1", echo=FALSE}
```
]
---
Then, we can assign variables in our data to different *aesthetics* of the plot.
.pull-left[
```{r our-first-plot-2, eval=FALSE}
ggplot(data = geo_data,
aes(x = ga_weeks, #<<
y = cg20970886)) #<<
```
This is referred to as *aesthetic mapping*.
]
.pull-right[
```{r our-first-plot-2-out, ref.label="our-first-plot-2", echo=FALSE}
```
]
---
Add **geometries (geoms)** to complete the plot.
.pull-left[
```{r our-first-plot-3, eval=FALSE}
ggplot(data = geo_data,
aes(x = ga_weeks,
y = cg20970886)) +
geom_point() #<<
```
Geoms are like saying what type of plot you want (e.g. scatterplot, boxplots, histograms... etc.)
]
.pull-right[
```{r our-first-plot-3-out, ref.label="our-first-plot-3", echo=FALSE}
```
]
---
There are many *geoms*. Sometimes it makes sense to combine several.
.pull-left[
```{r our-first-plot-4, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = ga_weeks,
y = cg20970886)) +
geom_point() + #<<
geom_smooth(method = "lm") #<<
```
]
.pull-right[
```{r our-first-plot-4-out, ref.label="our-first-plot-4", echo=FALSE, message=FALSE}
```
]
---
We can assign other variables to other aesthetics, e.g. color.
.pull-left[
```{r our-first-plot-5, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = ga_weeks,
y = cg20970886,
color = maternal_ethnicity)) + #<<
geom_point() +
geom_smooth(method = "lm")
```
But note that this assigned maternal ethnicity to the color of both points and lines!
]
.pull-right[
```{r our-first-plot-5-out, ref.label="our-first-plot-5", echo=FALSE, message=FALSE, warning = FALSE}
```
]
---
To assign color exclusively to points (and not lines), put inside specific geom:
.pull-left[
```{r our-first-plot-6, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = ga_weeks,
y = cg20970886)) +
geom_point(aes(color = maternal_ethnicity)) + #<<
geom_smooth(method = "lm")
```
]
.pull-right[
```{r our-first-plot-6-out, ref.label="our-first-plot-6", echo=FALSE, message=FALSE,warning=FALSE}
```
]
---
Can change the *shape* of points
.pull-left[
```{r our-first-plot-6-2, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = ga_weeks,
y = cg20970886)) +
geom_point(aes(color = maternal_ethnicity),
shape = 3) + #<<
geom_smooth(method = "lm")
```
See [reference](https://ggplot2.tidyverse.org/reference/scale_shape.html) for complete list of shapes.
]
.pull-right[
```{r our-first-plot-6-2-out, ref.label="our-first-plot-6-2", echo=FALSE, message=FALSE,warning=FALSE}
```
]
---
A common mistake is to forget the aesthetic call.
.pull-left[
```{r our-first-plot-7, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = ga_weeks,
y = cg20970886)) +
geom_point(color = "blue", #<<
shape = 3) +
geom_smooth(method = "lm")
```
]
.pull-right[
```{r our-first-plot-7-out, ref.label="our-first-plot-7", echo=FALSE, message=FALSE, warning = FALSE}
```
]
This assigns color to all the data
---
At this point, we've covered the 3 essential components to any ggplot2 plot:
1. **Data** - declare with a `ggplot(data = ...)` call
2. **Aesthetics** - assign input to plot components with `aes()`, e.g. (x/y position, color)
3. **Geoms** - declare the type of geometry, e.g. `+ geom_point()` for points
---
# There are so many geoms
Each geom has their own required aesthetics, and optional ones
- `geom_point` requires `x` and `y`, and that they be numeric variables
- `geom_boxplot` requires `x` and `y`, but `x` must be categorical
- `geom_histogram` and `geom_density` requires `x`
- `geom_text` requires `x`, `y`, and `text`
Check out [tidyverse site](https://ggplot2.tidyverse.org/reference/#section-geoms) for full list.
You can visit help pages for more information on a specific geom's options (e.g. `?geom_point`)
Now we know the basics, we can explore ways to customize our plots
---
.left-code[
```{r fine-tune-1-1, eval=FALSE, message = FALSE}
ggplot(data = geo_data) #<<
```
We'll start by looking at the methylation of this CpG site between preeclamptic and non-preeclamptic samples
First we declare the data.
]
.right-plot[
```{r fine-tune-1-1-out, ref.label="fine-tune-1-1", echo=FALSE, message=FALSE, warning = FALSE, out.height="100%"}
```
]
PE: diagnosed with preeclampsia
---
.left-code[
```{r fine-tune-1-2, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis, #<<
y = cg20970886, #<<
fill = diagnosis)) #<<
```
Then we declare the mappings of our variables to aesthetics
]
.right-plot[
```{r fine-tune-1-2-out, ref.label="fine-tune-1-2", echo=FALSE, message=FALSE, warning = FALSE, out.height="100%"}
```
]
PE: diagnosed with preeclampsia
---
.left-code[
```{r fine-tune-1-3, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() #<<
```
To specify we want boxplots, we use `geom_boxplot`
]
.right-plot[
```{r fine-tune-1-3-out, ref.label="fine-tune-1-3", echo=FALSE, message=FALSE, warning = FALSE, out.height="100%"}
```
]
PE: diagnosed with preeclampsia
---
.left-code[
```{r fine-tune-2-1, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_point() #<<
```
It can be informative to plot all individual data points over top of the boxplots.
To add individual data points, we simply add another geometry, `geom_point`
But it's a bit hard to see when the points overlap each other..
]
.right-plot[
```{r fine-tune-2-1-out, ref.label="fine-tune-2-1", echo=FALSE, message=FALSE, warning = FALSE}
```
]
---
.left-code[
```{r fine-tune-2-2, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() #<<
```
`geom_jitter` adds "noise" so that the points are spread out horizontally.
]
.right-plot[
```{r fine-tune-2-2-out, ref.label="fine-tune-2-2", echo=FALSE, message=FALSE, warning = FALSE}
```
]
---
layout: false
class: inverse center middle text-white
# Customizing your graphs
# Scales and themes
---
# Scales
`aes` determines which data variables are mapped to each component of the graph
`scale_*_*` functions determine *how* this mapping is done
`scale_<aes>_<type>` calls all start with "`scale_`" followed by the target aesthetic (e.g. x, y, color, fill), and finished by the type (e.g. discrete, continuous).
For example,
Want to change the limits on the y-axis? where the ticks appear? or maybe change to a log scale? Use
`scale_y_continuous(limits = c(0,1))` or
`scale_y_log10()`
Want to change colors? Use
`scale_color_discrete()` for categorical variables
`scale_color_continuous()` for continuous variables
---
.left-code[
```{r fine-tune-3, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) #<<
```
Here I assign specific colors to the categories of the diagnosis variable.
I supplied a vector of colors (can be in hex code) of same length of the number of categories of the variable `diagnosis`.
]
.right-plot[
```{r fine-tune-3-out, ref.label="fine-tune-3", echo=FALSE, message=FALSE, warning = FALSE}
```
]
---
.left-code[
```{r fine-tune-4-1, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("Controls", #<<
"Cases")) #<<
```
Here I change the labels of my x-axis.
]
.right-plot[
```{r fine-tune-4-1-out, ref.label="fine-tune-4-1", echo=FALSE, message=FALSE, warning=FALSE, out.width="100%"}
```
]
---
.left-code[
```{r fine-tune-4-2, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("non-PE" = "Controls", #<<
"PE" = "Cases")) #<<
```
It's better to be explicit about which label corresponds to which category
]
.right-plot[
```{r fine-tune-4-2-out, ref.label="fine-tune-4-2", echo=FALSE, message=FALSE, warning=FALSE, out.width="100%"}
```
]
---
.left-code[
```{r fine-tune-5, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("non-PE" = "Controls",
"PE" = "Cases")) +
scale_y_continuous(limits = c(0, 1), #<<
breaks = c(0, 0.5, 1)) #<<
```
Here I expand the y axis to 0 and 1, the natural range of methylation.
I also change where I want the ticks (i.e. "breaks") to appear.
Note that the y axis is a numeric variable and x axis is categorical, and how the respective scale calls reflect that.
]
.right-plot[
```{r fine-tune-5-out, ref.label="fine-tune-5", echo=FALSE, message=FALSE, warning=FALSE, out.width="100%"}
```
]
---
.left-code[
```{r fine-tune-6, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("non-PE" = "Controls",
"PE" = "Cases")) +
scale_y_continuous(limits = c(0, 1),
breaks = c(0, 0.5, 1)) +
theme(axis.text = element_text(colour = 'blue')) #<<
```
The **`theme()`** function call allows for a customization of the non-data components of a plot. Things like the title, labels, font size, gridlines, etc.
Pull up `?theme` to see a full description of all options
]
.right-plot[
```{r fine-tune-6-out, ref.label="fine-tune-6", echo=FALSE, message=FALSE, warning=FALSE, out.width="100%"}
```
]
---
.left-code[
```{r fine-tune-7, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("non-PE" = "Controls",
"PE" = "Cases")) +
scale_y_continuous(limits = c(0, 1),
breaks = c(0, 0.5, 1)) +
theme(axis.text = element_text(colour = 'blue'), #<<
panel.grid.major= element_line(colour = 'black'), #<<
panel.grid.minor = element_blank()) #<<
```
Most `theme()` arguments will require an "`element_*`" as input.
The type of element depends on the type of input (e.g. `element_text` for `axis.text`, `element_rect` for `panel.border`).
`element_blank` to remove components.
]
.right-plot[
```{r fine-tune-7-out, ref.label="fine-tune-7", echo=FALSE, message=FALSE, warning=FALSE, out.width="100%"}
```
]
---
.left-code[
```{r fine-tune-8, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("non-PE" = "Controls",
"PE" = "Cases")) +
scale_y_continuous(limits = c(0, 1),
breaks = c(0, 0.5, 1)) +
theme_bw(base_size = 20) #<<
```
There are some predefined themes that look nice and easy to use.
- `theme_gray` - default ggplot2 theme
- `theme_classic` - minimal with no gridlines
- `theme_bw` - clean look with white background
[List of complete ggplot2 themes](https://ggplot2.tidyverse.org/reference/ggtheme.html)
]
.right-plot[
```{r fine-tune-8-out, ref.label="fine-tune-8", echo=FALSE, message=FALSE, warning=FALSE, out.width="100%"}
```
]
---
.left-code[
```{r fine-tune-9, eval=FALSE, message = FALSE}
ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("non-PE" = "Controls",
"PE" = "Cases")) +
scale_y_continuous(limits = c(0, 1),
breaks = c(0, 0.5, 1)) +
theme_bw(base_size = 20) +
theme(legend.position = 'top') #<<
```
You can customize these complete themes by calling `theme()` after e.g. `theme_bw()`
]
.right-plot[
```{r fine-tune-9-out, ref.label="fine-tune-9", echo=FALSE, message=FALSE, warning=FALSE, out.width="100%"}
```
]
---
.left-code[
```{r save-1, eval=FALSE, message = FALSE}
p <- ggplot(data = geo_data, #<<
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("non-PE" = "Controls",
"PE" = "Cases")) +
scale_y_continuous(limits = c(0, 1),
breaks = c(0, 0.5, 1)) +
theme_bw(base_size = 20) +
theme(legend.position = 'top')
```
]
.right-plot[
There are a couple of options to save plots in R.
Probably the simplest way is to use `ggsave` from `ggplot2`.
First thing to do is to assign your plot into an object.
I assigned our plot to the object named `p`
]
---
.left-code[
```{r save-2, eval=FALSE, message = FALSE}
p <- ggplot(data = geo_data,
aes(x = diagnosis,
y = cg20970886,
fill = diagnosis)) +
geom_boxplot() +
geom_jitter() +
scale_fill_manual(values = c("orange", "#7ED7F2")) +
scale_x_discrete(labels = c("non-PE" = "Controls",
"PE" = "Cases")) +
scale_y_continuous(limits = c(0, 1),
breaks = c(0, 0.5, 1)) +
theme_bw(base_size = 20) +
theme(legend.position = 'top')
ggsave(plot = p, #<<
filename = "this-plot.png", #<<
device = 'png', #<<
dpi = 72, #<<
height = 5, #<<
width = 7) #<<
```
]
.right-plot[
Then we can call `ggsave` on object `p`.
I would recommend specifying the following options:
- `filename`, the name and location where you want the plot to be saved
- `device`, the type of image file (e.g. "pdf", "png", "tiff", etc...)
- `height`, `width` - determines the dimensions of your plot
- `dpi`, resolution
After you run the code, check your local directory for the png file.
]
---
# Resources
- Stack exchange for online help
- TOG study group / slack
- [Past TOG workshops](https://github.com/BCCHR-trainee-omics-group/StudyGroup)
- [ggplot2 extensions](https://exts.ggplot2.tidyverse.org/)
- [ggplot2 cheatsheet](https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf)
- [r 4 data science data visualization chapter](https://r4ds.had.co.nz/data-visualisation.html)
- [Eva Maerey's ggplot2 grammar guide](https://evamaerey.github.io/ggplot2_grammar_guide/about)
---