-
Notifications
You must be signed in to change notification settings - Fork 3
/
3_ggplot.Rmd
739 lines (563 loc) · 26.5 KB
/
3_ggplot.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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
---
title: "Data visualization in ggplot"
subtitle: "RNA-seq edition"
author: "Kim Dill-McFarland"
date: "version `r format(Sys.time(), '%B %d, %Y')`"
output:
html_document:
toc: yes
toc_depth: 4
toc_float:
collapsed: no
pdf_document:
toc: yes
toc_depth: '4'
editor_options:
chunk_output_type: console
urlcolor: blue
fig_width: 6
---
```{r, include=FALSE}
#set working dir to project
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
```
# 3. Data visualization in ggplot
In this workshop, we introduce you to data visualization in `ggplot` ([docs.ggplot2.org](http://docs.ggplot2.org/current/)), the [tidyverse](https://www.tidyverse.org/) package for plots. In it, we cover how to create:
* Volcano plot
* PCA plot
* Customization such as color, shape, theme
* Facets
During the workshop, we will build an R script together, which will be posted as 'live_notes' after the workshop at <https://github.com/BIGslu/workshops/tree/main/2022.08.15_R.tidyverse.workshop/live_notes>
We load `ggplot` within the `tidyverse.` For more information on installation, see the [setup instructions][lesson0].
```{r}
library(tidyverse)
```
## Intro to ggplot
### Why ggplot?
ggplot2 is an implementation of _Grammar of Graphics_ (Wilkinson 1999) for R
Benefits:
- handsome default settings
- snap-together building block approach
- automatic legends, colors, facets
- statistical overlays like regressions lines and smoothers (with confidence intervals)
Drawbacks:
- it can be hard to get it to look *exactly* the way you want
- requires having the input data in a certain format
### ggplot layers
`ggplot` functions by adding layers to a plot, somewhat like how `dplyr`/`tidyr` sequentially modify data with the pipe `%>%`. Instead, `ggplot` uses the `+` to combine layers such as:
- _data_: 2D table (`data.frame`) of _variables_
- _aesthetics_: map variables to visual attributes (position, color, etc)
- _geoms_: graphical representation of data (points, lines, etc)
- _stats_: statistical transformations to get from data to points in
the plot (binning, summarizing, smoothing)
- _scales_: control how to map a variable to an aesthetic
- _facets_: juxtapose mini-plots of data subsets, split by variables
- _guides_: axes, legend, etc. that reflect the variables and their values
The idea is to independently specify and combine layers to create the plot you want. There are at least three things we have to specify to create any plot:
1. data
2. aesthetic mappings from data variables to visual properties
3. a geom describing how to draw those properties
## Data
A quick reminder about our data. There are bulk RNA-seq contained in the `dat` object in file "data/dat_voom.RData". Normalized log2 counts per million (CPM) are contained in `dat$E` and library metadata are in `dat$targets`. You will not need the other pieces of `dat` for this workshop.
```{r}
load("data/dat_voom.RData")
dat$E[1:3,1:3]
dat$targets[1:3,]
```
Here is a brief description of the variables in the metadata.
* `libID` (character): Unique library ID for each sequencing library. Formatted as ptID_condition
* `ptID` (character): Patient ID. Each patient has 2 libraries which differ in their `condition`
* `condition` (character): Experimental condition. Media for media control. Mtb of *M. tuberculosis* infected.
* `age_dys` (numeric): Age in ages
* `sex` (character): Biological sex, M or F
* `ptID_old` (character): Old patient ID with leading zeroes
* `RNAseq` (logical): If the library has pass-filter RNA-seq data
* `methylation` (logical): If the library has pass-filter methylation data
* `total_seq` (numeric): Total number of pass-filter sequences
## Basic plots
### Boxplot
We will start with a boxplot of the total sequences per library. First, we call a ggplot object. Since we've given it no data or aesthetics, this is a blank plot.
```{r}
ggplot()
```
Then, we give the plot data and specify aesthetics for which parts of the data we want to plot. Now, we see that ggplot knows what the scale of the y data will be. Throughout this section, we will highlight lines of code that change with the comment `#<--- see change`.
```{r}
ggplot(dat$targets) +
aes(y = total_seq) #<--- see change
```
Finally, we add a geom to denote how we want the data displayed, in this case as a boxplot.
```{r}
ggplot(dat$targets) +
aes(y = total_seq) +
geom_boxplot() #<--- see change
```
Since we did not specify an x-variable, all the data are plotted in one boxplot. We add an aesthetic to specify x and split up the data.
```{r}
ggplot(dat$targets) +
aes(y = total_seq, x = condition) + #<--- see change
geom_boxplot()
```
### Data ordering with factors
Our x-variable happens to be in the correct alphabetical order with the `Media` controls before `Mtb` infection. However, alphabetical does not always give you want you want. You can force a variable's order by converting it to a factor. Let's switch the `condition` order.
```{r}
dat$targets %>%
mutate(condition_fct = factor(condition,
levels = c("Mtb", "Media"))) %>% #<--- see change
ggplot() +
aes(y = total_seq, x = condition_fct) +
geom_boxplot()
```
Notice how we now pipe `%>%` the data into ggplot so that we can modify it in `dplyr` first.
### Dotplot
These same data could be displayed as a dotplot instead. We return to the original `condition` order since it was correct.
```{r}
ggplot(dat$targets) +
aes(y = total_seq, x = condition) +
geom_point() #<--- see change
```
And if we want to make sure we see every point, a jitter works nicely.
```{r}
ggplot(dat$targets) +
aes(y = total_seq, x = condition) +
geom_jitter() #<--- see change
```
### Multiple geoms
The building block nature of ggplot allows us to add multiple geoms on top of each other. So we can combine the two previous plots like so
```{r}
ggplot(dat$targets) +
aes(y = total_seq, x = condition) +
geom_boxplot() + #<--- see change
geom_jitter() #<--- see change
```
But you may notice that there are some duplicate points. Looking back at the first boxplots, there are points for data outside the box. These points remain in the above plot plus appear jittered from the second geom. We can fix this by telling the boxplot to not plot the outliers.
```{r}
ggplot(dat$targets) +
aes(y = total_seq, x = condition) +
geom_boxplot(outlier.shape = NA) + #<--- see change
geom_jitter()
```
#### Layer order matters
Because ggplot works in layers, the order matters. If, for example, we put the boxplot after the jitter, the boxes cover up points! We use `alpha` for transparency so you can see these points. Thus, be careful when considering how you setup your plot!
```{r}
ggplot(dat$targets) +
aes(y = total_seq, x = condition) +
geom_jitter() + #<--- see change
geom_boxplot(outlier.shape = NA, alpha = 0.8) #<--- see change
```
#### Why are my dots moving?
With jitter, you are adding random error to be able to see all the points. Because this is truly random, every time you run jitter, you will get a slightly different plot. To combat this, set a seed before making the plot.
```{r}
set.seed(468) #<--- see change
ggplot(dat$targets) +
aes(y = total_seq, x = condition) +
geom_boxplot(outlier.shape = NA) +
geom_jitter()
set.seed(468) #<--- see change
ggplot(dat$targets) +
aes(y = total_seq, x = condition) +
geom_boxplot(outlier.shape = NA) +
geom_jitter()
```
## RNA-seq plots
### PCA
One dotplot of interest in RNA-seq analysis is principle component analysis (PCA). In this plot, each RNA-seq library is a single point. The axes are unitless but in general, points that are closer together represent libraries with more similar gene expression. You can see large scale changes in gene expression in PCA. However, even when you don't see clear PCA groupings, there can be significant differentially expressed genes. So don't despair if your data don't cluster in this plot!
Here, we calculate PCA from the normalized counts. Note that we transpose `t()` the counts data to get one PCA point per library, instead of one per gene.
```{r}
dat.pca <- prcomp(t(dat$E), scale.=TRUE, center=TRUE)
dat.pca$x[1:3,1:3]
```
Then we use join to add metadata to the PCA data, so we can annotate the PCA plot with variables of interest.
```{r}
dat.pca.meta <- as.data.frame(dat.pca$x) %>%
rownames_to_column("libID") %>%
inner_join(dat$targets)
```
A nice trick with joins is to not specify what to join `by`. In this case, the function finds all columns shared between the data frames and uses them to match rows.
With `geom_point`, we have a PCA!
```{r}
ggplot(dat.pca.meta) +
aes(x = PC1, y = PC2) +
geom_point()
```
#### Color and shape
But it's not very informative, so let's annotate with our condition groups. In general, you want to use annotations in the following order: space, color, shape, size. These are ordered by how easily the human eye can discern differences.
We already have space as libraries are separated along x and y. Now we add color.
```{r}
ggplot(dat.pca.meta) +
aes(x = PC1, y = PC2, color = condition) + #<--- see change
geom_point()
```
I like to keep all my aesthetics in one layer, but you could keep adding `aes()` functions to the plot if you prefer. This gives the same plot.
```{r eval=FALSE}
ggplot(dat.pca.meta) +
aes(x = PC1, y = PC2) + #<--- see change
geom_point() +
aes(color = condition) #<--- see change
```
We could also use shape for the same data. Which plot to you think is easier to interpret?
```{r}
ggplot(dat.pca.meta) +
aes(x = PC1, y = PC2, shape = condition) + #<--- see change
geom_point()
```
We're not showing size or transparency because these aesthetics are difficult to see and should be avoided unless you *really* need them or the differences between data points are large enough to see in these aesthetics.
#### Labels
We can also improve our axes and legend labels. First, we see what proportion of variation is explained by each PC.
```{r}
summary(dat.pca)$importance
```
And use that for labels as well as change the legend.
```{r}
ggplot(dat.pca.meta) +
aes(x = PC1, y = PC2, color = condition) +
geom_point() +
labs(x = "PC1 (24%)", y = "PC2 (11%)", #<--- see change
color = "Infection")
```
#### Coordinates
Since PCA units are relative, it is nice to have the scales of the x and y be the same. That is, 1 inch of space corresponding to the same values for both. This is accomplished with `coord_fixed`. Note that in this PCA, this function does not change the plot much but it can can a big effect in other PCA! There are also several other coordinate systems you can see with `coord_`.
```{r}
ggplot(dat.pca.meta) +
aes(x = PC1, y = PC2, color = condition) +
geom_point() +
labs(x = "PC1 (24%)", y = "PC2 (11%)",
color = "Infection") +
coord_fixed() #<--- see change
```
#### Themes
`ggplot` has a number of themes that change the aesthetics of the plot. I like `theme_classic` for PCA. Type `theme_` into the console to see the available themes suggested with auto-complete. You can also checkout more themes in the package `ggthemes`.
```{r}
ggplot(dat.pca.meta) +
aes(x = PC1, y = PC2, color = condition) +
geom_point() +
labs(x = "PC1 (24%)", y = "PC2 (11%)",
color = "Infection") +
coord_fixed() +
theme_classic() #<--- see change
```
### volcano plot
Let's move on to another application of `geom_point`. A volcano plot shows differentially expressed gene significance and fold change.
#### Linear modeling
We'll need to perform linear modeling to determine these results. Below is the workflow for comparing Mtb-infected vs media samples, corrected for sex and blocked by patient. We use our R package [`kimma`](https://github.com/BIGslu/kimma). You **DO NOT** need to run these steps. They are here in case you want to run a similar analysis in the future.
```{r eval=FALSE}
install.packages("devtools")
devtools::install_github("BIGslu/kimma")
```
```{r eval=FALSE}
library(kimma)
```
```{r eval=FALSE}
fit <- kmFit(dat, model = "~ condition + sex + (1|ptID)",
run.lme = TRUE, use.weights = TRUE)
```
```
lme/lmerel model: expression~condition+sex+(1|ptID)
Input: 20 libraries from 10 unique patients
Model: 20 libraries
Complete: 13419 genes
Failed: 0 genes
```
```{r eval=FALSE}
save(fit, file="data/kimma_result.RData")
```
Instead, load the results from the data downloaded for this workshop. Note that this is an S3 object similar to the `dat` object. In it, we have the linear mixed effects (lme) model results in `fit$lme`, which includes our log2 fold change `estimate` and significance `FDR` for each gene and each variable.
```{r}
load("data/kimma_result.RData")
fit$lme
```
#### Color
Let's start with a basic dotplot like before. We first filter the fit data to just the variable `condition` so that we have 1 point per gene.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
ggplot() +
aes(x = estimate, y = -log10(FDR)) +
geom_point()
```
Now let's color the significant points. There is no "significant" variable in the data frame, so we first make one with mutate.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 ~ "FDR < 0.01", #<--- see change
TRUE ~ "NS")) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR), color = significance) + #<--- see change
geom_point()
```
Or go further and color up vs down regulated genes differently.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down", #<--- see change
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR), color = significance) +
geom_point()
```
And we can specify the colors we want with another layer.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR), color = significance) +
geom_point() +
scale_color_manual(values = c("blue", "grey", "red")) #<--- see change
```
#### Lines
Since we're defining significance at a cutoff, we can plot that cutoff with a vertical line with `geom_vline`. Other similar geoms are `geom_hline` for a horizontal line and `geom_abline` for a line with slope `a` and intercept `b`.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR), color = significance) +
geom_point() +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) #<--- see change
```
#### Scales
You might also wish to center the 0 estimate or otherwise alter the plots limits.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR), color = significance) +
geom_point() +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
lims(x = c(-9, 9)) #<--- see change
```
If you accidentally (or purposefully) remove data point with your limits, R will warn you!
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR), color = significance) +
geom_point() +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
lims(x = c(-3, 3)) #<--- see change
```
#### Label points
We're going to use a ggplot extension package to label our most significant genes. Let's load that package now.
```{r}
library(ggrepel)
```
First, we determine our top 2 up and down regulated genes. There are some new `dplyr` functions in here! See the comments for information.
```{r}
top_deg <- fit$lme %>%
filter(variable == "condition") %>%
mutate(direction = case_when(estimate < 0 ~ "down",
estimate > 0 ~ "up")) %>%
group_by(direction) %>%
slice_min(FDR, n=2) %>% # Keeps n number of minimum FDR values
pull(gene) # Extract the variable and turns the data into a vector
top_deg
```
Then we add those labels to our fit data and use that variable in `geom_text_repel`. In this case, the data removal warning is expected as we're not labeling the majority of points.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
mutate(label = case_when(gene %in% top_deg ~ gene)) %>% #<--- see change
ggplot() +
aes(x = estimate, y = -log10(FDR), color = significance) +
geom_point() +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
lims(x = c(-9, 9)) +
geom_text_repel(aes(label = label)) #<--- see change
```
The text legend gets overlayed with the point legend, which looks odd. Let's remove one of them.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
mutate(label = case_when(gene %in% top_deg ~ gene)) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR), color = significance) +
geom_point() +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
lims(x = c(-9, 9)) +
geom_text_repel(aes(label = label), show.legend = FALSE) #<--- see change
```
And a small edit if you don't want the text to be colored. When you put an aesthetic in a specific geom, it only applies that change to that one geom.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
mutate(label = case_when(gene %in% top_deg ~ gene)) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR)) + #<--- see change
geom_point(aes(color = significance)) + # <--- see change
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
lims(x = c(-9, 9)) +
geom_text_repel(aes(label = label), show.legend = FALSE)
```
#### Theme
To round it out, let's look at `theme_bw`, my favorite one for volcano plots.
```{r}
fit$lme %>%
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
mutate(label = case_when(gene %in% top_deg ~ gene)) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR)) +
geom_point(aes(color = significance)) +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
lims(x = c(-9, 9)) +
geom_text_repel(aes(label = label)) +
theme_bw() #<--- see change
```
There you have it! Did you think you'd reach a 11 function plot so soon?
#### Facets
With big data, we often want to plot more than one thing at once. Facets allow you to make similar plots across multiple subsets of data with only 1 additional line of code. Here, we filter for 2 `variable` and then facet those into 2 plots.
```{r}
fit$lme %>%
filter(variable %in% c("condition", "sex")) %>% #<--- see change
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
mutate(label = case_when(gene %in% top_deg ~ gene)) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR)) +
geom_point(aes(color = significance)) +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
#<--- see change No lims used
geom_text_repel(aes(label = label)) +
theme_bw() +
facet_wrap(~ variable) #<--- see change
```
Since the a and y scales differ for the two variable, we allow them to differ with `scales`. This is my we removed the `lims` function earlier. `scales` can be set to "free_x", "free_y", or "free" for both x and y.
```{r}
fit$lme %>%
filter(variable %in% c("condition", "sex")) %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
mutate(label = case_when(gene %in% top_deg ~ gene)) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR)) +
geom_point(aes(color = significance)) +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
geom_text_repel(aes(label = label)) +
theme_bw() +
facet_wrap(~ variable, scales = "free") #<--- see change
```
### Save plots
Once you have your plot as you desire, save it to your computer for use in presentations, publications, Twitter, and more! `ggsave` allows you to save in a bunch of formats (see the help page with `?ggsave`).
Since we've only been printing our plots to the plot pane in RStudio, we need to first save a plot to the environment. We'll use the single `condtion` variable volcano plot.
```{r}
p1 <- fit$lme %>% #<--- see change
filter(variable == "condition") %>%
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
mutate(label = case_when(gene %in% top_deg ~ gene)) %>%
ggplot() +
aes(x = estimate, y = -log10(FDR)) +
geom_point(aes(color = significance)) +
scale_color_manual(values = c("blue", "grey", "red")) +
geom_hline(yintercept = -log10(0.01)) +
geom_text_repel(aes(label = label)) +
theme_bw()
p1
```
Now we can save the object. My most commonly used plot formats are `.pdf` for publication (vectorized PDF that can be edited in Illustrator/Inkscape) and `.png` for all other uses (not vectorized, smaller files). You specify the file type in the filename and give dimensions in inches (default). Without dimensions, R used whatever the ratio of you plot pane currently is (not reproducible!).
```{r}
ggsave(filename = "images/volcano_plot.png", plot = p1, width = 3, height = 4)
ggsave(filename = "images/volcano_plot.pdf", plot = p1, width = 3, height = 4)
```
## Commented plot scripts
Here are each of the final plots fulled comments for your reference.
```{r eval = FALSE}
ggplot(dat.pca.meta) + # Make ggplot from data in dat.pca.meta
aes(x = PC1, y = PC2, # Plot PCs 1 and 2 along x and y
color = condition) + # Color by condition
geom_point() + # Plot points for each value
labs(x = "PC1 (24%)", y = "PC2 (11%)", # Relabel axes
color = "Infection") + # Relabel legend
coord_fixed() + # Force xy scales to be equal
theme_classic() # Set theme
```
```{r eval = FALSE}
fit$lme %>%
# Keep results for only the condition variable
filter(variable == "condition") %>%
# Create variable for significant up and down genes
mutate(significance = case_when(FDR < 0.01 & estimate < 0 ~ "down",
FDR < 0.01 & estimate > 0 ~ "up",
TRUE ~ "NS")) %>%
# Create variable for gene name labels
mutate(label = case_when(gene %in% top_deg ~ gene)) %>%
ggplot() + # initiate ggplot plot
aes(x = estimate, y = -log10(FDR)) + # plot estimate and FDR
geom_point(aes(color = significance)) + # plot points, color by significance
scale_color_manual(values = c("blue", "grey", "red")) + # recolor points
geom_hline(yintercept = -log10(0.01)) + # add FDR cuttof line
lims(x = c(-9, 9)) + # set axis limits
geom_text_repel(aes(label = label)) + # label points
theme_bw() # set theme
```
```{r eval = FALSE}
... +
facet_wrap(~ variable) # facet by variable
```
## Exercises: ggplot
1. Using the combined expression and metadata you made in the last session, plot the expression of one gene in `Media` vs `Mtb`. The plot type is up to you! As a reminder, here is how we made the combined data.
```{r}
full_data <- as.data.frame(dat$E) %>%
rownames_to_column("gene") %>%
pivot_longer(-gene, names_to = "libID", values_to = "log2CPM") %>%
inner_join(dat$targets)
full_data
```
2. Color the PCA by the numeric variable `total_seq`. Explore the help pages for `scale_color_continuous`, `scale_color_gradient`, or `scale_color_gradient2` and recolor your PCA to more easily see differences. As a reminder, here is the base PCA plot.
```{r}
ggplot(dat.pca.meta) +
aes(x = PC1, y = PC2) +
geom_point() +
labs(x = "PC1 (24%)", y = "PC2 (11%)",
color = "Infection") +
theme_classic()
```
3. Using `geom_text_repel`, label the points in the PCA by their `libID`
# *Navigation*
* [Workshop index][index]
* Previous lesson: [Data visualization in ggplot][lesson3]
* [Lesson source code][lesson3rmd]
***
[index]: https://bigslu.github.io/workshops/2022.08.15_R.tidyverse.workshop/index.html
[lesson0]: https://bigslu.github.io/workshops/2022.08.15_R.tidyverse.workshop/0_setup.html
[lesson1]: https://bigslu.github.io/workshops/2022.08.15_R.tidyverse.workshop/1_introR.html
[lesson2]: https://bigslu.github.io/workshops/2022.08.15_R.tidyverse.workshop/2_tidyverse.html
[lesson3]: https://bigslu.github.io/workshops/2022.08.15_R.tidyverse.workshop/3_ggplot.html
[lesson1rmd]: https://github.com/BIGslu/workshops/blob/main/2022.08.15_R.tidyverse.workshop/1_introR.Rmd
[lesson2rmd]: https://github.com/BIGslu/workshops/blob/main/2022.08.15_R.tidyverse.workshop/2_tidyverse.Rmd
[lesson3rmd]: https://github.com/BIGslu/workshops/blob/main/2022.08.15_R.tidyverse.workshop/3_ggplot.Rmd
[workshop]: https://bigslu.github.io/workshops/2022.08.15_R.tidyverse.workshop/R_tidyverse_RNAseq_edition.html