-
Notifications
You must be signed in to change notification settings - Fork 1
/
supplemental_file_A.Rmd
2594 lines (2266 loc) · 116 KB
/
supplemental_file_A.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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
bibliography: references.bib
biblio-style: apalike
highlight_bw: yes
output:
bookdown::pdf_document2:
toc: false
includes:
in_header: header.tex
dev: "cairo_pdf"
latex_engine: xelatex
fig_caption: yes
geometry: margin=0.45in
link-citations: yes
---
**Supplemental File A of**
\begingroup\Large
**MicrobiotaProcess: A comprehensive R package for deep mining microbiome**
\endgroup
**Shuangbin Xu, Li Zhan, Wenli Tang, Qianwen Wang, Zehan Dai, Lang Zhou, Tingze Feng, Meijun Chen, Tianzhi Wu, Erqiang Hu and Guangchuang Yu\* **
^\*^correspondence: Guangchuang Yu \<gcyu1@smu.edu.cn\>
\renewcommand{\figurename}{Fig.}
\newcommand{\beginsupplement}{%
\setcounter{table}{0}
\renewcommand{\thetable}{SA.\arabic{table}}%
\setcounter{figure}{0}
\renewcommand{\thefigure}{SA.\arabic{figure}}%
}
\beginsupplement
```{r, echo=FALSE, message=FALSE, results='hide'}
require(kableExtra)
options(knitr.table.fromat = "latex")
knitr::opts_chunk$set(fig.pos= "!ht")
#knitr::opts_chunk$set(out.width="90%")
knitr::opts_chunk$set(fig.align="center", warning = FALSE, message = FALSE)
usepackage_latex("float")
usepackage_latex("makecell")
usepackage_latex("booktabs")
Biocpkg <- function (pkg){
sprintf("[%s](http://bioconductor.org/packages/%s)", pkg, pkg)
}
CRANpkg <- function(pkg){
cran <- "https://CRAN.R-project.org/package"
fmt <- "[%s](%s=%s)"
sprintf(fmt, pkg, cran, pkg)
}
knitr::knit_hooks$set(crop = knitr::hook_pdfcrop)
knitr::opts_chunk$set(crop = TRUE)
```
```{r setup, echo = FALSE, results = 'hide', message = FALSE}
suppressPackageStartupMessages({
library(SummarizedExperiment) # SummarizedExperiment container, a container contains one or more assays.
library(MicrobiotaProcess) # an R tidy framework for microbiome or other related ecology data analysis.
library(ggplot2) # Create Elegant Data Visualisations Using the Grammar of Graphics.
library(coin) # Conditional Inference Procedures in a Permutation Test Framework.
library(ggnewscale) # Multiple Fill and Colour Scales in 'ggplot2'.
library(forcats) # Helpers for reordering factor levels and tools for modifying factor levels.
library(ggtree) # visualizing phylogenetic tree and heterogenous associated data based on grammar of graphics.
library(ggtreeExtra) # plot associated data on the external layer based on grammar of graphics.
library(clusterProfiler)
library(enrichplot)
library(MicrobiomeProfiler)
library(curatedMetagenomicData)
library(randomForest)
})
```
# Installation
To install `MicrobiotaProcess` package, please enter the following command in R:
```r
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("MicrobiotaProcess")
```
To reproduce the analysis in this document, the several extra packages also needed to be installed.
```r
cranpkgs <- c("aplot", "ggpp", "igraph",
"broom", "forcats", 'pROC',
"ggrepel", "ggVennDiagram",
"patchwork", "shadowtext",
"ggupset", "ggnewscale",
"GUniFrac", "matrixStats")
for (i in cranpkgs){
if (!requireNamespace(i, quietly = TRUE)){
install.packages(i)
}
}
Biocpkgs <- c("SummarizedExperiment", "clusterProfiler",
"edgeR", "enrichplot", "tidybulk", "curatedMetagenomicData",
"ggtree", "ggtreeExtra", "MicrobiomeProfiler")
for (i in Biocpkgs){
if (!requireNamespace(i, quietly = TRUE)){
BiocManager::install(i)
}
}
```
# Analysis of 16s rDNA dataset about 43 pediatric CD stool samples from iHMP {#chapter2}
Here, we re-analyzed the 16s rDNA dataset of 43 pediatric IBD stool samples, which were obtained from the Integrative Human Microbiome Project Consortium (iHMP) [@iHMP].
## Importing the output of dada2 {#chapter2.1}
The datasets were downloaded from the web^[<https://www.microbiomeanalyst.ca/MicrobiomeAnalyst/resources/data/ibd_data.zip>]. These datasets contain `ibd_asv_table.txt` (feature table (*row features* X *column samples*)), `ibd_meta.csv` (metadata file of samples), and `ibd_taxa.txt` (the taxonomic annotation of features). In the session, we used *mp_import_dada2* of *MicrobiotaProcess* to import the dataset, and returned an *MPSE* object.
```{r, message=FALSE, warning=FALSE, fold.plot=FALSE, fold.output=FALSE, LoadData}
library(MicrobiotaProcess)
otuda <- read.table("./data/IBD_data/ibd_asv_table.txt", header=T,
check.names=F, comment.char="", row.names=1, sep="\t")
# building the output format of removeBimeraDenovo of dada2
otuda <- data.frame(t(otuda), check.names=F)
sampleda <- read.csv("./data/IBD_data/ibd_meta.csv", row.names=1, comment.char="")
taxda <- read.table("./data/IBD_data/ibd_taxa.txt", header=T,
row.names=1, check.names=F, comment.char="")
# the feature names should be the same with rownames of taxda.
taxda <- taxda[match(colnames(otuda), rownames(taxda)),]
ref.tree <- treeio::read.tree('./data/IBD_data/ibd_repseq.tree')
mpse <- mp_import_dada2(seqtab = otuda, taxatab = taxda, sampleda = sampleda)
# view the reads depth of samples and the prevalence of the OTUs. In this example,
# mpse %>% mp_extract_assay(.abundant=Abundance) %>% rowSums() %>% sort %>% head(100)
# mpse %>% mp_extract_assay(.abundant=Abundance) %>% colSums() %>% sort %>% head()
# Or
# head(sort(rowSums(assay(mpse, "Abundance"))), 100)
# head(sort(colSums(assay(mpse, "Abundance"))))
# In this example, we can find some OTUs have very low frequency in the samples.
# and some taxonomy are unreasonable, for example, the probability of chloroplasts
# in the intestine should be low. We can also remove the features.
mpse2 <- mpse %>%
dplyr::filter(!Phylum %in% c("p__un_k__Bacteria", "p__Chloroflexi") &
!Class %in% "c__Chloroplast" &
!Family %in% "f__mitochondria"
) %>%
mp_filter_taxa(.abundance = Abundance, min.abun = 1, min.prop = 0.1)
otutree(mpse2) <- ref.tree
mpse2
```
```{r, echo = FALSE}
if (!dir.exists(file.path("./TmpRef"))){
dir.create("./TmpRef")
}
saveRDS(mpse, file="./TmpRef/mpse.rds")
```
## Other import functions {#chapter2.2}
*MicrobiotaProcess* also presents some other functions \ref{tab:importFuns} to parse the output of the upstream pipelines. In addition, some common objects of R can also be converted to *MPSE* object, such as *phyloseq* [@phyloseq], *SummarizedExperiment* [@SE], *TreeSummarizedExperiment* [@TSE], *biom* [@biom] (output of *biomformat* by *read_biom*) referring to session \ref{chapter3.1}.
```{r, echo=FALSE, results='asis', importFuns}
x <- "MicrobiotaProcess\tmp_import_qiime2\tImport function to load the output of qiime2\n
MicrobiotaProcess\tmp_import_qiime\tImport function to read the now legacy-format QIIME OTU table (tsv format)\n
MicrobiotaProcess\tmp_import_metaphlan\tImport function to read the output of MetaPhlAn\n
"
xx <- base::strsplit(x, "\n\n")[[1]]
y <- base::strsplit(xx, "\t") %>% do.call("rbind", .)
y <- as.data.frame(y)
colnames(y) <- c("Package", "Import Function", "Description")
suppressPackageStartupMessages(require(kableExtra))
caption = "List of import functions provided by MicrobiotaProcess"
knitr::kable(y, caption = caption, booktabs = T) %>%
collapse_rows(columns = 1, latex_hline = "major", valign ="middle") %>%
kable_styling(latex_options = c("striped", "hold_position")) #%>% landscape
```
## alpha diversity analysis {#chapter2.3}
### rarefaction visualization {#chapter2.3.1}
Rarefaction based on the sampling technique was used to compensate for the effect of sample size on the number of units observed in a sample. *MicrobiotaProcess* provides *mp_cal_rarecurve* and *mp_plot_rarecurve* to calculate and plot the curves.
(ref:rarecurve1) **This example shows *mp_cal_rarecurve* and *mp_plot_rarecurve* provided by *MicrobiotaProcess* to calculate and visualize the rarefaction curve.** The horizontal coordinate represents the sequencing depth of samples, the vertical coordinate shows the Alpha diversity index (such as Observe OTU, Chao1 and ACE). The *mp_plot_rarecurve* provides three types of visualization. (A) the rarefaction curve for each sample. (B) the rarefaction curve for each sample with colored group (specified *.group* argument in *mp_plot_rarecurve*). (C) the rarefaction curve for each group with standard error of the mean (specified *.group* argument and *plot.group=TRUE* in *mp_plot_rarecurve*)
```{r class.source = 'fold-show', fold.output=FALSE, fold.plot=FALSE, fig.width=7, fig.height=6, fig.align="center",warning=FALSE, message=FALSE, fig.cap='(ref:rarecurve1)', rarecurve1}
library(MicrobiotaProcess)
library(patchwork)
cols <- c('#fcc751ff', '#00c7bfff')
mpse2 %<>%
mp_rrarefy(.abundance=Abundance) %>%
mp_cal_rarecurve(.abundance=RareAbundance, chunks=500)
p_rare <- mpse2 %>%
mp_plot_rarecurve(
.rare = RareAbundanceRarecurve,
.alpha = c(Observe, Chao1, ACE),
) +
theme(
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm"),
legend.spacing.y = unit(0.01,"cm"),
legend.text = element_text(size=4)
)
prare1 <- mpse2 %>%
mp_plot_rarecurve(
.rare = RareAbundanceRarecurve,
.alpha = c(Observe, Chao1, ACE),
.group = Group
) +
scale_fill_manual(values = cols)+
scale_color_manual(values = cols)+
theme_bw()+
theme(
axis.text=element_text(size=8), panel.grid=element_blank(),
strip.background = element_rect(colour=NA,fill="grey"),
strip.text.x = element_text(face="bold")
)
prare2 <- mpse2 %>%
mp_plot_rarecurve(
.rare = RareAbundanceRarecurve,
.alpha = c(Observe, Chao1, ACE),
.group = Group,
plot.group = TRUE
) +
scale_color_manual(values = cols)+
scale_fill_manual(values = cols) +
theme_bw()+
theme(
axis.text=element_text(size=8), panel.grid=element_blank(),
strip.background = element_rect(colour=NA,fill="grey"),
strip.text.x = element_text(face="bold")
)
(p_rare / prare1 / prare2) + patchwork::plot_annotation(tag_levels="A")
```
\newpage
```{r echo = FALSE}
prare1 <- prare1 +
theme(
legend.position=c(0.1, 0.8),
legend.key.width = unit(.3, "cm"),
legend.key.height = unit(.3, 'cm'),
legend.text = element_text(size = 6)
)
ggsave(prare1, file = "./Figures/rarecurve.svg", device="svg", width=7, height=3)
```
<!-- Since the curves in each sample were near saturation, the sequencing data were great enough with very few new species undetected -->
### Calculation and different analysis of alpha diversity {#chapter2.3.2}
Alpha diversity can evaluate the richness and evenness of microbial communities. *MicrobiotaProcess* provides *mp_cal_alpha* to calculate alpha index. Six common diversity measures (*Observe*, *Chao1*, *ACE*, *Shannon*, *Simpson*, *Pielou*) are supported. In addition, *MicrobiotaProcess* also provided *mp_cal_pd_metric* to calculate some phylogenetic community structure metrics, such as PD (Faith's Phylogenetic Diversity), NRI (Nearest Relative Index), NTI (Nearest Taxon Index), IAC (Relative deviation from null expectation of phylogenetically balanced abundances), PAE (Phylogenetic evenness of the abundance distribution scaled by branch lengths), HAED (Entropic measure of diversity of evolutionary distinctiveness among individuals), EAED (Equitability of HAED) [@PhylogeneticMetric2; @PhylogeneticMetric]. These phylogenetic metrics can help us to explore the process of microbiota community assembly [@PhylogeneticMetric]. The result can be visualized by *mp_plot_alpha*. The following example showed how to use *mp_cal_alpha* and *mp_plot_alpha* of *MicrobiotaProcess* to analyze the alpha diversity of the community. The *RareAbundance* is rarefied (default), which will be used to calculate the alpha diversity index, users can specify the *force=TRUE* of *mp_cal_alpha* to calculated the alpha diversity if the abundance can not be rarefied (referring to session \ref{chapter3.3.1}).
(ref:AlphaBox) **The raincloud plot of alpha diversity index** The horizontal coordinate represents each group (by *.group* argument of *mp_plot_alpha*), the vertical coordinate represents the alpha diversity index.
```{r fig.width=8, fig.height=3, fig.align="center", warning=FALSE, message=FALSE, fig.cap='(ref:AlphaBox)', AlphaBox}
library(MicrobiotaProcess)
mpse2 %<>% mp_cal_alpha(.abundance = RareAbundance)
p_alpha <- mpse2 %>%
mp_plot_alpha(
.alpha = c(Observe, Chao1, ACE, Shannon, Simpson, Pielou),
.group = Group,
) +
scale_fill_manual(values=cols) +
scale_color_manual(values=cols) +
theme(
legend.position="none",
strip.background = element_rect(colour=NA, fill="grey")
)
p_alpha
```
```{r echo = FALSE}
ggsave(p_alpha, file = "./Figures/alpha.svg", device = "svg", width = 7, height = 3.8)
```
(ref:AlphaBox2) The raincloud plot of phylogenetic diversity index. The horizontal coordinate represents each group (by *.group* argument of *mp_plot_alpha*), the vertical coordinate represents the phylogenetic diversity index.
```{r, fig.width=8, fig.height=3, fig.align="center", warning=FALSE, message=FALSE, fig.cap='(ref:AlphaBox2)', AlphaBox2}
mpse2 %<>% mp_cal_pd_metric(.abundance = RareAbundance, metric = all)
p.pd_alpha <- mpse2 %>%
mp_plot_alpha(
.alpha = c("PAE", "NRI", "NTI", "PD", "HAED", "EAED", "IAC"),
.group = Group,
) +
scale_fill_manual(values=cols)+
scale_color_manual(values=cols) +
theme(legend.position="none",
strip.background = element_rect(colour=NA, fill="grey"))
p.pd_alpha
```
```{r echo = FALSE}
p.alpha2 <- mpse2 %>%
mp_plot_alpha(
.alpha = c(Observe, Shannon, Pielou, NRI, PD, HAED),
.group = Group,
) +
scale_fill_manual(values = cols) +
scale_color_manual(values = cols) +
theme(
legend.position = "none",
strip.background = element_rect(colour=NA, fill="grey"),
panel.border=element_rect(linewidth=.2),
axis.ticks=element_line(linewidth=.2)
)
p.alpha2$layers[[2]]$aes_params$size <- .8
p.alpha2$layers[[2]]$aes_params$stroke <- .1
p.alpha2$layers[[3]]$aes_params$size <- .4
p.alpha2$layers[[4]]$aes_params$size <- .2
ggsave(p.alpha2, file = './Figures/alpha2.svg', device = 'svg', width = 7, height = 3.8)
```
\newpage
<!--
These metrics might provide new clues for the diagnosis of disease. We used each the significant differential metric (100 random samples) to calculate the AUC, then found the vast majority of AUC scores are greater than 0.65.
(ref:PdAUC) The box plot of the AUC score based on the significant differential alpha diversity metrics.
```{r, fig.width = 5.6, fig.height = 4, fig.align = 'center', warning = FALSE, message = FALSE, fig.cap = '(ref:PdAUC)', PdAUC}
generate_random_sample <- function(dat, prob=2/3){
dat %>%
dplyr::group_split(Group) %>%
lapply(function(x)x[sample(nrow(x), size=prob * nrow(x)),]) %>%
dplyr::bind_rows()
}
mpse2 %>%
mp_extract_sample %>%
select(Sample, Observe, IAC, NRI, HAED, PD, Group) %>%
tibble::column_to_rownames(var='Sample') -> dat
pd.roc.res <- replicate(100,
pROC::roc(formula=Group ~ Observe+IAC+NRI+HAED+PD,
data = generate_random_sample(dat),
levels=c('Control', 'CD'),
quiet = TRUE,
) %>%
lapply(function(x)as.numeric(x$auc)) %>%
unlist()
)
pd.roc.p <- pd.roc.res %>%
magrittr::set_colnames(value=paste0('Sample', seq_len(100))) %>%
tibble::as_tibble(rownames='Metrics') %>%
tidyr::pivot_longer(cols=!Metrics, names_to='Sample', values_to='AUC') %>%
ggplot(aes(x=AUC, y=Metrics, fill=Metrics)) +
geom_boxplot() +
geom_jitter(height=.3, color='grey') +
theme_bw() +
theme(legend.position='none') +
ylab(NULL)
pd.roc.p
```
-->
## Taxonomy composition analysis {#chapter2.4}
### Statistics and visualization of specific levels {#chapter2.4.1}
*MicrobiotaProcess* presents the *mp_cal_abundance* and *mp_plot_abundance* for the calculation and visualization of the composition of microbial communities. After the *mp_cal_abundance* is done, you can get the abundance of specific levels of the class by *mp_extract_abundance* (referring to session \ref{chapter2.5.4}).
(ref:Abundance1) **The relative abundance of each sample in *class* level**
```{r fig.width=8.5, fig.height=4, fig.align="center", warning=FALSE, message=FALSE, fig.cap="(ref:Abundance1)", Abundance1}
library(ggplot2)
library(MicrobiotaProcess)
# The relative abundance of all taxonomy for samples will be calculated
mpse2 %<>% mp_cal_abundance(.abundance = RareAbundance)
# The relative abundance of all taxonomy for group will be calculated
mpse2 %<>% mp_cal_abundance(.abundance = RareAbundance, .group = Group)
# The 30 most abundant taxonomy will be visualized.
pclass <- mpse2 %>%
mp_plot_abundance(
.abundance = RareAbundance,
.group = Group,
taxa.class = Class,
topn = 30
) +
xlab(NULL) +
ylab("relative abundance (%)") +
theme(
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm")
) +
xlab(NULL) +
ylab("relative abundance (%)") +
theme(
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm"),
legend.text = element_text(size=6)
)
pclass
```
```{r, echo = FALSE}
ggsave(pclass, filename = "./Figures/AbundanceBar.svg", device = "svg", height=4, width = 8.5)
```
The relative abundance of different groups also can be visualized by providing *.group* argument and setting *plot.group=TRUE* in the *mp_plot_abundance*. If you want to view the raw abundance (count or others) of taxa, you can set the *relative* parameter of *mp_plot_abundance* to *FALSE*.
(ref:Abundance2) **This example show how to displayed the abundance (count or other) of sample and the relative abundance of groups**. The relative abundance of group (A) and the abundance (count by rarefied) of each sample (B), these results show the *Gammaproteobacteria* of *CD* group might be more abundant than the *control* group.
```{r fig.width=12, fig.height=6, fig.cap='(ref:Abundance2)', warning=FALSE, message=FALSE, fig.align="center", Abundance2}
# Show the abundance in different groups.
fclass <- mpse2 %>%
mp_plot_abundance(
.abundance = RareAbundance,
.group = Group,
taxa.class = Class,
topn = 30,
plot.group = TRUE
) +
xlab(NULL) +
ylab("relative abundance (%)") +
theme(legend.position = "none")
pclass2 <- mpse2 %>%
mp_plot_abundance(
.abundance = RareAbundance,
.group = Group,
relative = FALSE,
taxa.class = Class,
topn = 30
) +
xlab(NULL) +
ylab("count reads") +
theme(
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm"),
legend.text = element_text(size=6)
)
aplot::plot_list(pclass2, fclass, widths=c(10, 1), tag_levels = "A")
```
The abundance of features also can be visualized using *mp_plot_abundance* with heatmap plot by setting `geom="heatmap"`.
(ref:AbundanceHeatmap) **The heatmap of abundance for each sample at *class* level.** The color (continuous) of heatmap represents the abundance of different classes, the color of bar plot represents the group name of sample, the horizontal coordinate represents the sample, and the vertical coordinate represents the different classes.
```{r, fig.width = 12, fig.height = 4, fig.align = "center", fig.cap = '(ref:AbundanceHeatmap)', warning=FALSE, message=FALSE, AbundanceHeatmap}
hclass1 <- mpse2 %>%
mp_plot_abundance(
.abundance = RareAbundance,
.group = Group,
taxa.class = Class,
topn = 30,
geom = "heatmap"
) %>%
set_scale_theme(
x = list(scale_fill_viridis_c(option = "H"),
theme(
axis.text.x = element_text(size = 6),
axis.text.y = element_text(size = 7),
legend.title = element_text(size = 7),
legend.text = element_text(size = 5),
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm")
)
),
aes_var = RelRareAbundance
) %>%
set_scale_theme(
x = list(scale_fill_manual(values = cols),
theme(
legend.key.height = unit(0.3, "cm"),
legend.key.width = unit(0.3, "cm"),
legend.spacing.y = unit(0.02, "cm"),
legend.text = element_text(size = 7),
legend.title = element_text(size = 9)
)
),
aes_var = Group
)
hclass2 <- mpse2 %>%
mp_plot_abundance(
.abundance = RareAbundance,
.group = Group,
taxa.class = Class,
topn = 30,
geom = 'heatmap',
relative = FALSE
) %>%
set_scale_theme(
x = list(scale_fill_viridis_c(option = "H"),
theme(
axis.text.x = element_text(size = 6),
axis.text.y = element_text(size = 7),
legend.title = element_text(size = 7),
legend.text = element_text(size = 5),
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm")
)
),
aes_var = RareAbundance
) %>%
set_scale_theme(
x = list(scale_fill_manual(values = cols),
theme(
legend.key.height = unit(0.3, "cm"),
legend.key.width = unit(0.3, "cm"),
legend.spacing.y = unit(0.02, "cm"),
legend.text = element_text(size = 7),
legend.title = element_text(size = 9)
)
),
aes_var = Group
)
p <- aplot::plot_list(hclass1, hclass2, nrow = 1, tag_levels = "A")
p
```
```{r, echo = FALSE}
ggsave(hclass1, filename = "./Figures/Abunheat.svg", device = "svg", width = 7, height = 5)
```
### Venn or Upset plot {#chapter2.4.2}
The Venn or UpSet plot can help us to obtain the difference between groups in the overview. *MicrobiotaProcess* provides *mp_cal_venn* (*mp_plot_venn*) and *mp_cal_upset* (*mp_plot_upset*) to perform the analysis.
(ref:VennUpsetPlot) **The Venn diagram and upset plot for groups in OTU/ASV level**
```{r, fig.width=5, fig.height=5, fig.align="center", warning=FALSE, message=FALSE, fig.cap="(ref:VennUpsetPlot)", VennUpsetPlot}
mpse2 %<>%
mp_cal_venn(
.abundance = RareAbundance,
.group = Group
)
venn_p <- mpse2 %>%
mp_plot_venn(
.group = Group,
set_size = 2.5,
label_size = 2,
edge_size = 2.5
) +
scale_colour_manual(values = cols) +
scale_fill_viridis_c(guide = guide_colorbar(barwidth=.3, barheight=2)) +
theme(
legend.title = element_text(size = 8),
legend.text = element_text(size = 6)
)
mpse2 %<>%
mp_cal_upset(
.abundance = RareAbundance,
.group = Group
)
upset_p <- mpse2 %>%
mp_plot_upset(
.group = Group
) +
theme_bw() +
theme(
plot.background = element_blank(),
panel.border = element_blank(),
panel.grid = element_blank(),
axis.line.x.bottom = element_line(size = .5),
axis.line.y.left = element_line(size = .5)
) +
ggupset::theme_combmatrix(
combmatrix.label.extra_spacing = 40
)
library(ggpp)
p.up.venn <- upset_p +
ggpp::annotate(
"plot_npc",
npcx = "right",
npcy = "top",
label = venn_p,
vp.width = 0.6,
vp.height = 0.4
)
p.up.venn
```
```{r echo = FALSE}
ggsave(p.up.venn, filename = "./Figures/upset.svg", device = "svg", width = 5, height = 5)
```
## beta analysis {#chapter2.5}
### PCA analysis {#chapter2.5.1}
`PCA` (Principal Component Analysis) and `PCoA` (Principal Coordinate Analysis) are general statistical procedures to compare dissimilarity of samples. And `PCoA` can based on the phylogenetic or count-based distance metrics, such as `Bray-Curtis`, `Jaccard`, `Unweighted-UniFrac` and `weighted-UniFrac`. *MicrobiotaProcess* presents the *mp_cal_dist*, *mp_cal_pca*, *mp_cal_pcoa*, *mp_cal_dca*, *mp_cal_nmds*, *mp_cal_cca*, *mp_cal_rda*, *mp_adonis*, *mp_anosim*, *mp_mrpp*, *mp_envfit* and *mp_mantel* for the related analysis.
(ref:PCAplot) **The PCA plot of the community**. Each point represents one sample, the size of point represents the observe OTU of the sample. The color of point represents the group name of the sample, based on the first and second component (A), based on the first and third component (B).
```{r , fig.width=10, fig.height=4, fig.align="center", warning=FALSE, message=FALSE, fig.cap="(ref:PCAplot)", PCAplot}
library(MicrobiotaProcess)
library(patchwork)
# hellinger transform
mpse2 %<>%
mp_decostand(
.abundance = Abundance,
method = "hellinger"
)
mpse2 %<>% mp_cal_pca(.abundance = hellinger)
# Visulizing the result
pcaplot1 <- mpse2 %>%
mp_plot_ord(
.ord = pca,
.group = Group,
.starshape = Group,
.size = Observe
) +
scale_fill_manual(values = cols) +
scale_size_continuous(
range = c(1, 3),
guide = guide_legend(override.aes = list(starshape = 15))
) +
theme(
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm"),
legend.text = element_text(size = 6),
legend.title = element_text(size = 7)
)
# .dim = c(1, 3) to show the first and third principal components.
pcaplot2 <- mpse2 %>%
mp_plot_ord(
.ord = pca,
.dim = c(1, 3),
.group = Group,
.starshape = Group,
.size = Observe
) +
scale_fill_manual(values = cols) +
scale_size_continuous(
range = c(1, 3),
guide = guide_legend(override.aes = list(starshape = 15))
) +
theme(
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm"),
legend.text = element_text(size = 6),
legend.title = element_text(size = 7)
)
(pcaplot1 | pcaplot2) + plot_annotation(tag_levels = "A")
```
### PCoA analysis {#chapter2.5.2}
(ref:PCoAplot) **The PCoA plot based on Bray-Curtis distance**.
```{r, fig.width=10, fig.height=4, fig.align="center", warning=FALSE, message=FALSE, fig.cap="(ref:PCoAplot)", PCoAplot}
# distmethod
# "unifrac", "wunifrac", "manhattan", "euclidean", "canberra", "bray", "kulczynski" ...(vegdist, dist)
mpse2 %<>%
mp_cal_dist(
.abundance = hellinger,
distmethod = "bray"
)
# PCoA analysis
mpse2 %<>%
mp_cal_pcoa(
.abundance = hellinger,
distmethod = "bray"
)
pcoaplot1 <- mpse2 %>%
mp_plot_ord(
.ord = pcoa,
.group = Group,
.starshape = Group,
.color = Group,
.size = Observe,
ellipse = TRUE,
show.legend = FALSE
) +
scale_color_manual(
values = cols
) +
scale_fill_manual(values = cols) +
scale_size_continuous(
range = c(1, 3),
guide = guide_legend(override.aes = list(starshape = 15))
) +
theme(
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm"),
legend.text = element_text(size=6),
legend.title = element_text(size=7)
)
# first and third principal co-ordinates
pcoaplot2 <- mpse2 %>%
mp_plot_ord(
.ord = pcoa,
.group = Group,
.starshape = Group,
.color = Group,
.size = Observe,
ellipse = TRUE,
.dim = c(1, 3),
show.legend = FALSE
) +
scale_color_manual(
values = cols
) +
scale_fill_manual(
values = cols
) +
scale_size_continuous(
range = c(1, 3),
guide = guide_legend(override.aes = list(starshape = 15))
) +
theme(
legend.key.width = unit(0.3, "cm"),
legend.key.height = unit(0.3, "cm"),
legend.text = element_text(size = 6),
legend.title = element_text(size = 7)
)
(pcoaplot1 | pcoaplot2) + plot_annotation(tag_levels = "A")
```
```{r, echo = FALSE}
ggsave(pcoaplot1, filename="./Figures/pcoa.svg", width = 5, height = 4, device = "svg")
```
The result of distance between the samples also can be visualized by `mp_plot_dist` with heatmap or boxplot.
(ref:distplot) **The distance heatmap and the boxplot for each sample**. The size and color of the heatmap represent the distance of each sample, and color of bar plot represents the group of sample (A). The boxplot represents the distance pairs of sample among the group, it shows the dissimilarity of the sample between the *control* and *CD* is significant, which is consistent with the result of the Permutational Multivariate Analysis of Variance in session \ref{chapter2.5.3}.
```{r, fig.width = 10, fig.height = 6, fig.align="center", message = FALSE, fig.cap = '(ref:distplot)', distplot}
pdist1 <- mpse2 %>%
mp_plot_dist(
.distmethod = bray,
.group = Group
) %>%
set_scale_theme(
x = scale_fill_manual(
values=cols,
guide = guide_legend(
keywidth = 0.5,
keyheight = 0.5,
label.theme=element_text(size=6)
)
),
aes_var = Group
) %>%
set_scale_theme(
x = list(scale_size_continuous(range = c(1, 3)),
scale_color_viridis_c(option = "H"),
theme(
legend.key.width = unit(0.3, "cm"),
legend.text = element_text(size = 6),
legend.title = element_text(size = 7)
)
),
aes_var = bray
)
pdist2 <- mpse2 %>%
mp_plot_dist(
.distmethod = bray,
.group = Group,
group.test = TRUE
) +
scale_color_manual(
values = c("orange", "#00A08A", "deepskyblue")
) +
scale_fill_manual(
values = c("orange", "#00A08A", "deepskyblue")
)
aplot::plot_list(pdist1, pdist2, widths = c(3, 1), nrow=1, tag_levels = "A")
```
\newpage
### Permutational Multivariate Analysis of Variance {#chapter2.5.3}
We also can perform the Permutational Multivariate Analysis of Variance using *mp_adonis* wrapping the *adonis* of *vegan* [@vegan].
```{r}
mpse2 %<>% mp_adonis(.abundance = hellinger, distmethod = "bray",
.formula = ~Group, permutation = 9999, action = "add")
mpse2 %>% mp_extract_internal_attr(name=adonis) %>% mp_fortify()
```
From the result, we found the *pvalue* of the analysis of *adonis* is smaller than 0.05 for the `Group`, meaning the dissimilarity of samples between the `Group` is significant, which is consistent with the \ref{chapter2.5.2}.
### hierarchical cluster analysis of samples {#chapter2.5.4}
`beta diversity` metrics can assess the differences between microbial communities. It can be visualized with `PCA` or `PCoA`, it also can be visualized with hierarchical clustering based on ggplot2 [@ggplot2], ggtree [@ggtree2017] and ggtreeExtra [@ggtreeExtra]
(ref:HClustplot) **The hierarchical clustering plot of samples based on Bray-Curtis distance calculated with abundance of OTU/ASV and the relative Abundance of phyla for samples**
```{r fig.width=7, fig.height=5, fig.align="center", warning=FALSE, message=FALSE, fig.cap="(ref:HClustplot)", HClustplot}
library(ggplot2)
library(MicrobiotaProcess)
library(ggtree)
library(ggtreeExtra)
mpse2 %<>%
mp_cal_clust(.abundance = hellinger, distmethod = "bray", action = "add")
hcsample <- mpse2 %>% mp_extract_internal_attr(name=SampleClust)
# rectangular layout + relative abundance of phyla
phy.tb <- mpse2 %>%
mp_extract_abundance(
taxa.class = Phylum,
topn = 30
) %>%
tidyr::unnest(cols=RareAbundanceBySample) %>%
dplyr::rename(Phyla="label")
cplot1 <- ggtree(hcsample, layout = "rectangular") +
geom_treescale(fontsize = 2) +
geom_tippoint(mapping=aes(color=Group)) +
geom_fruit(
data = phy.tb,
geom = geom_col,
mapping = aes(x = RelRareAbundanceBySample, y = Sample, fill = Phyla),
orientation = "y",
offset = 0.08,
pwidth = 3,
width = .6,
axis.params = list(
axis = "x",
title = "The relative abundance of phyla (%)",
title.size = 3,
title.height = 0.04,
text.size = 2,
vjust = 1
)
) +
geom_tiplab(as_ylab = TRUE) +
scale_color_manual(
values = cols,
guide = guide_legend(
keywidth = .5,
keyheight = .5,
title.theme = element_text(size = 8),
label.theme = element_text(size = 6)
)
) +
scale_fill_manual(
values=c(colorRampPalette(RColorBrewer::brewer.pal(12,"Set2"))(6)),
guide = guide_legend(
keywidth = .5,
keyheight = .5,
title.theme = element_text(size = 8),
label.theme = element_text(size = 6)
)
) +
scale_x_continuous(expand = c(0, 0.01))
cplot1
```
```{r, echo = FALSE}
ggsave(cplot1, filename = "./Figures/sample.clust.svg", device = "svg", width = 7, height = 5)
```
\newpage
## biomarker discovery {#chapter2.6}
This package provides `mp_diff_analysis` to detect the biomarker. And the result (with `action = "get"`) can be visualized by *ggdiffbox*, *ggdiffclade*, *ggeffectsize*, *ggdifftaxbar* and *mp_plot_diff_res* *mp_plot_diff_cladogram* (with `action = "add"`), or displayed manually using `ggtree` [@ggtree2017] and `ggtreeExtra` [@ggtreeExtra].
(ref:DeCladogram) **The cladogram of significant differential taxa between CD group and Control group** The hight light clades represent the differential taxa is enriched in the corresponding group. We found the species from Proteobacteria were enriched in the CD group, the species (OTU_42) from Actinobacteria were enriched in Control group.
```{r warning=FALSE, message=FALSE, fig.width = 10, fig.height=10, fig.align='center', fig.cap='(ref:DeCladogram)', DeCladogram}
# for the kruskal_test and wilcox_test
library(coin)
library(MicrobiotaProcess)
# get result (diffAnalysisClass) of the different analysis with action = 'get'.
deres <- mpse2 %>%
mp_diff_analysis(
.abundance = RareAundance,
.group = Group,
first.test.method = "kruskal_test",
filter.p = "pvalue",
first.test.alpha = 0.05,
strict = TRUE,
second.test.method = "wilcox_test",
second.test.alpha = 0.05,
subcl.min = 3,
subcl.test = TRUE,
ml.method = "lda",
ldascore = 3,
action = "get"
)
# The result of different analysis was added to the taxatree with action = 'add'
mpse2 <- mpse2 %>%
mp_diff_analysis(
.abundance = RareAundance,
.group = Group,
first.test.method = "kruskal_test",
filter.p = "pvalue",
first.test.alpha = 0.05,
strict = TRUE,
second.test.method = "wilcox_test",
second.test.alpha = 0.05,
subcl.min = 3,
subcl.test = TRUE,
ml.method = "lda",
ldascore = 3,
action = "add"
)
p.clado <- mpse2 %>%
mp_plot_diff_cladogram(
taxa.class = Order,
removeUnknown = TRUE,
as.tiplab = TRUE,
tip.annot = TRUE,
label.size = 2.2
) +
scale_fill_diff_cladogram(values=cols)
p.clado
```
\newpage
```{r echo=FALSE}
ggsave(p.clado, filename="./Figures/diff_cladogram.cd.svg", device="svg", width = 10, height = 10)
```
### visualization of different results by `ggdiffclade` {#chapter2.6.1}
The color of discriminative taxa represents the taxa is more abundant in the corresponding group. The point size shows the negative logarithms (base 10) of the pvalue. The bigger size of the point shows more significant (lower pvalue), the *pvalue* was calculated in the first step test (default is *kruskal.test*).
(ref:DiffClade) **The taxa tree clade plot of different analysis result (with action = 'get')**.
```{r eval = FALSE, fig.width=12, fig.height=12, fig.align="center", warning=FALSE, message=FALSE, fig.cap="(ref:DiffClade)", DiffClade}
diffclade_p <- ggdiffclade(
obj=deres,
alpha=0.3,
linewd=0.15,
skpointsize=0.6,
layout="radial",
taxlevel=3,
removeUnkown = TRUE,
reduce = FALSE # This argument is to remove the branch of unknown taxonomy.
) +
scale_fill_manual(
values = cols
) +
guides(color = guide_legend(
keywidth = 0.1,
keyheight = 0.2,
order = 3,
ncol=1)
) +
theme(
panel.background = element_rect(fill=NA),
legend.position = "right",
plot.margin = ggplot2::margin(0,0,0,0),
legend.key.width = unit(0.2, "cm"),
legend.key.height = unit(0.2, "cm"),
legend.spacing.y = unit(0.02, "cm"),
legend.title = element_text(size=7),
legend.text = element_text(size=6),
legend.box.spacing = unit(0.02,"cm")
)
diffclade_p
```
We also can visualized the result (default, with `action = 'add'`) via `ggtree` [@ggtree2017] and `ggtreeExtra` [@ggtreeExtra].
(ref:DiffAllplot) **The taxa tree of the community with the relative abundance of each OTU/ASV on sample and the LDA of different OTU/ASV**. The taxa tree was built with the taxa of all samples. The high light clades of taxa tree represented the phyla. The external point layer represented the relative abundance of each OTU on sample. The external bar plot represented the LDA of the different OTU. The colored points represented the different taxa, the size of colored point represented the *pvalue* or *fdr*.
```{r, fig.width = 10, fig.height=10, fig.align="center", fig.cap = '(ref:DiffAllplot)', DiffAllplot}
taxa.tree <- mpse2 %>% mp_extract_tree(type='taxatree')
p1 <- ggtree(
taxa.tree,
layout="radial",
size = 0.3
) +
geom_point(
data = td_filter(!isTip),
fill="white",
size=1,
shape=21
)
# display the high light of phylum clade.
p2 <- p1 +
geom_hilight(
data = td_filter(nodeClass == "Phylum"),
mapping = aes(node = node, fill = label)
)