--- title: "Metagenomic" output: rmarkdown::html_vignette: toc: true toc_depth: 3 fig_caption: true bibliography: references.bib link-citations: true vignette: > %\VignetteIndexEntry{Metagenomic} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include=FALSE} knitr::opts_chunk$set( fig.align = "center", out.width = "100%", fig.width = 7, fig.height = 5, dpi = 96 ) ``` 🍄 This tutorial shows how to use `MicroBioMeta` on **shotgun metagenomic** data, as an alternative to the amplicon (metabarcoding) workflow covered in the [Metabarcoding vignette](metabarcoding.html). The functions and most of their parameters are exactly the same across both workflows, so they aren't re-explained here; only what's specific to metagenomic data is. The installation instructions are in the [Metabarcoding vignette](metabarcoding.html). For this example, reads were taxonomically classified with [`Kraken2`](https://ccb.jhu.edu/software/kraken2/) [@wood2019kraken2] and abundance-corrected at the species level with [`Bracken`](https://ccb.jhu.edu/software/bracken/) [@lu2017bracken]. The data comes from forest soils along the Iztaccíhuatl-Popocatépetl (PNIP) and La Malinche (PNML) transects, Central Mexico: [Hereira-Pacheco, S. E. et al. (2025). Metagenomic analysis of fungal assemblages at a regional scale in high-altitude temperate forest soils: alternative methods to determine diversity, composition and environmental drivers. *PeerJ*, 13, e18323.](https://peerj.com/articles/18323/) Raw data, metadata and the original analysis scripts: [github.com/Steph0522/Fungal_Metagenomes_PNIP_PNML](https://github.com/Steph0522/Fungal_Metagenomes_PNIP_PNML) ## Loading data First, let's load `MicroBioMeta` and `tidyverse` (used for data wrangling): ```{r load, message=FALSE} library("MicroBioMeta") library(tidyverse) ``` Each sample was processed separately, so `bracken_species` reports were merged into a single table beforehand (one column per sample, named `kraken_pluspfp__report_bracken_species`) with a **`taxonomy`** column already attached as the last column: ```{r data-1} table_kraken <- read.delim( system.file("extdata", "table_kraken.txt", package = "MicroBioMeta"), row.names = 1, check.names = FALSE ) table_kraken[1:3, c(1:2, ncol(table_kraken))] ``` Taxonomy is already in the table, so there is no need to use the `merge_feature_taxonomy()` function. ⚠️ Taxonomy strings from Kraken2 use a `k__`/`p__`/`c__`/... prefix like SILVA, but ranks are separated by `"; "` (semicolon **and space**) instead of `";"`. `MicroBioMeta` already accounts for this wherever a `taxonomy_db` argument exists, just pass `taxonomy_db = "Kraken2"`. Now, let's load the metadata: ```{r data-2} metadata_meta <- read.delim( system.file("extdata", "metadata_metagenomic.txt", package = "MicroBioMeta"), check.names = FALSE ) head(metadata_meta[, 1:10]) ``` Kraken column names encode a `id_metagenome` number (e.g. `kraken_pluspfp_100_report_bracken_species`) rather than the sample's actual ID, so we recover it with a regular expression and use `metadata_meta$id_metagenome` to rename each column to its `SampleID`: ```{r data-3} sample_cols <- setdiff(colnames(table_kraken), "taxonomy") id_metagenome <- as.integer(gsub("kraken_pluspfp_|_report_bracken_species", "", sample_cols)) colnames(table_kraken)[match(sample_cols, colnames(table_kraken))] <- metadata_meta$SAMPLEID[match(id_metagenome, metadata_meta$id_metagenome)] ``` Let's rename and format the metadata: ```{r data-4} metadata_meta$Polygon <- factor(paste0("Pol", metadata_meta$Poligono), levels = paste0("Pol", 1:6)) metadata_meta$Site <- as.character(metadata_meta$Sitio) ``` ```{r data-5} table_meta <- table_kraken[, c(metadata_meta$SAMPLEID, "taxonomy")] ``` Coordinates were taken and loaded: ```{r data-6} coord_meta <- read.csv( system.file("extdata", "coord_metagenomic.csv", package = "MicroBioMeta") ) %>% dplyr::select(-Site) %>% # drop the CSV's own overall site index (1-12); we want `Sitio` (1-2) instead dplyr::rename(Polygon_num = pol, Site = Sitio) %>% dplyr::select(Polygon_num, Site, Transecto, Latitude, Longitude) metadata_meta <- metadata_meta %>% dplyr::mutate(Polygon_num = as.integer(gsub("Pol", "", Polygon)), Site = as.integer(Site)) %>% dplyr::left_join(coord_meta, by = c("Polygon_num", "Site", "Transecto")) %>% dplyr::mutate(Site = as.character(Site)) ``` ### Starting from a phyloseq or TreeSummarizedExperiment object `MicroBioMeta` works with plain tables, but if your data are already in a `phyloseq` object or in a `TreeSummarizedExperiment` (the Bioconductor container used by the [`mia`](https://bioconductor.org/packages/mia/) family of packages), `from_phyloseq()` and `from_tse()` turn them into the `table` (with the `taxonomy` column last) and `metadata` (with `SAMPLEID` first) used in this vignette. To show it, we pack the Kraken2 table into a `TreeSummarizedExperiment`, with one taxonomy column per rank, as `mia` would: ```{r tse-1, eval=requireNamespace("TreeSummarizedExperiment", quietly = TRUE), message=FALSE} counts <- as.matrix(table_meta[, metadata_meta$SAMPLEID]) ranks <- tidyr::separate( data.frame(taxonomy = gsub("[kpcofgs]__", "", table_meta$taxonomy)), taxonomy, c("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species"), sep = "; ", fill = "right" ) rownames(ranks) <- rownames(table_meta) samples <- metadata_meta rownames(samples) <- samples$SAMPLEID tse <- TreeSummarizedExperiment::TreeSummarizedExperiment( assays = list(counts = counts), rowData = ranks, colData = samples ) tse ``` `from_tse()` returns a list with the two data frames: ```{r tse-2, eval=requireNamespace("TreeSummarizedExperiment", quietly = TRUE)} mbm <- from_tse(tse, assay_name = "counts") mbm$table[1:3, c(1:2, ncol(mbm$table))] mbm$metadata[1:3, 1:5] ``` and those can go straight into any function, e.g. `abundance_bar_plot(table = mbm$table, metadata = mbm$metadata, ...)`. With a `phyloseq` object it works the same way: ```{r tse-3, eval=FALSE} mbm <- from_phyloseq(physeq) ``` ## Composition exploration ### Abundance barplot Same function as in the metabarcoding vignette; the only difference is `taxonomy_db = "Kraken2"`, which tells the taxonomy-parsing logic to expect Kraken2/Bracken-style strings. ```{r bar, fig.width=9, fig.height=6} abundance_bar_plot( table = table_meta, metadata = metadata_meta, taxonomy_db = "Kraken2", level = "genus", top_n = 20, x_col = "Polygon", x_axis_title = "Polygons", add_remained = TRUE, label = "Genus", save_table = FALSE ) ``` ### Abundance heatmap Kraken2/Bracken taxa aren't ASVs, so `feature_prefix = "Taxon"` is used here instead of the default `"ASV"` row-label prefix. `condition2` adds a second annotation bar, here the sampling site within each polygon. ```{r heat, warning=FALSE, fig.width=8.5, fig.height=5.5, out.width="85%"} abundance_heatmap_plot( table = table_meta, metadata = metadata_meta, top_n = 20, show_column_names = FALSE, condition1 = "Polygon", condition2 = "Site", feature_prefix = "Taxon" ) ``` ## Alpha diversity As in the metabarcoding vignette, `alpha_hill_corr_plot(table = table_meta)` can be used first to check whether the Hill numbers depend on sequencing depth. ### Alpha diversity visualization `fill_col` is the same as `x_col` here, so the legend would just repeat the x-axis tick labels - `show_legend = FALSE` drops it. ```{r alpha, warning=FALSE, fig.width=9, fig.height=5} alpha_hill_plot( table = table_meta, metadata = metadata_meta, x_col = "Polygon", fill_col = "Polygon", facet_by = "Site", facet_orientation = "horizontal", legend_title = "", stat = "kruskal.test", show_legend = FALSE, save_table = FALSE ) ``` Richness (*q*=0) is nearly saturated and flat across polygons here — this species-level Bracken table has only 87 fungal species, 83 of them present in all 36 samples, so there is little room left to vary at *q*=0 — while *q*=1 and *q*=2 (which weight by relative abundance) do pick up differences between polygons. ### Alpha diversity along a continuous gradient ```{r alpha-gradient, warning=FALSE, fig.height=4, fig.width=10} alpha_decay_plot( table = table_meta, metadata = metadata_meta, cont_var = "pH", x_axis_title = "Soil pH" ) ``` Diversity at *q*=1 and *q*=2 increases significantly with soil pH; *q*=0 doesn't, for the same ceiling-effect reason as above. ## Beta diversity ### Ordination of community composition Here we use **Bray-Curtis** dissimilarity, which takes into account the abundance of each taxon, with an **NMDS** ordination. NMDS starts from random configurations, so we use `set.seed()` to get the same plot every time: ```{r ord, warning=FALSE, message=FALSE, fig.width=8, fig.height=6} set.seed(123) beta_ord_plot( table = table_meta, metadata = metadata_meta, distance = "bray", ordination = "NMDS", group_col = "Polygon" ) ``` ### Statistical tests for beta diversity `distance = "bray"` matches the one used for the ordination above, so the ordination (via the `vegan` package [@oksanen2024vegan]) and the PERMANOVA significance test [@anderson2001permanova] are evaluating the same notion of dissimilarity. The result is a table figure (a ggplot), so it can be combined with other plots (e.g. `cowplot::plot_grid()`) or saved with `ggplot2::ggsave()`. Use `save_table = TRUE` to also get the results as a text file. ```{r permanova, fig.width=8, fig.height=4} beta_test_table( table = table_meta, metadata = metadata_meta, formula_str = "Polygon*Site", distance = "bray", test = "permanova", permutations = 999 ) ``` ### Distance-decay of community similarity `beta_decay_plot()` tests whether communities that are geographically closer are also more similar in composition, via a Mantel test [@mantel1967test]: ```{r decay, warning=FALSE, fig.width=5.5, fig.height=4.2, out.width="70%"} beta_decay_plot( table = table_meta, metadata = metadata_meta, lat_col = "Latitude", lon_col = "Longitude", distance = "bray" ) ``` Communities that are geographically closer are significantly more similar in composition (Mantel *r* ≈ 0.21, *p* ≈ 0.001; the exact p-value jitters slightly between runs since the Mantel test is permutation-based), a real distance-decay signal across these forest soils. The relationship is weak, though: distance explains only about 4 % of the variation in similarity (R² ≈ 0.04). `bray` is used to be consistent with the ordination above. ## Differential abundance analysis For the heatmap (ALDEx2 [@fernandes2014aldex2]) and ANCOM-BC2 [@lin2024ancombc2] versions we need a 2-group subset of the 6-level `Polygon`, in this part we will compare Polygon 2 and 5: ```{r diff-1} metadata_meta_compar <- metadata_meta %>% filter(Polygon == "Pol2" | Polygon == "Pol5") table_meta_compar <- table_meta[, c(match(metadata_meta_compar$SAMPLEID, colnames(table_meta)), ncol(table_meta))] ``` ```{r diff-2, fig.width=6, fig.height=6, message=FALSE, warning=FALSE, out.width="50%"} aldex_heatmap_plot( table = table_meta_compar, metadata = metadata_meta_compar, group_col = "Polygon" ) ``` ```{r diff-3, fig.width=8, fig.height=6, message=FALSE, warning=FALSE, out.width="50%"} ancombc_plot( table = table_meta_compar, metadata = metadata_meta_compar, group_col = "Polygon", level = "Genus", min_prevalence = 0.05, p_adjust_method = "BH" ) ``` ### Identifying important taxa `random_forest_lollipop_plot()` uses a Random Forest model [@breiman2001randomforest] to find the taxa that best predict the polygon: ```{r rf-1, fig.width=7, fig.height=6, out.width="60%"} random_forest_lollipop_plot(table = table_meta, metadata = metadata_meta, top_n = 10, variable_to_predict = "Polygon") ``` ```{r rf-2, fig.width=8, fig.height=9, out.width="60%"} ratios_bubble_plot( table = table_meta_compar, metadata = metadata_meta_compar, group_col = "Polygon", top_n = 20, condition_A = "Pol2", condition_B = "Pol5" ) ``` ## Environmental analyses The metadata already carries the soil physicochemical variables measured for these samples, so, as in the metabarcoding vignette, the variables are chosen by name with `env_vars` (no separate environmental table is needed): ```{r env-table} env_vars_meta <- metadata_meta %>% dplyr::select(pH:ARENA, -type, -type2) %>% colnames() ``` ### Correlation between environmental variables and taxonomic abundance ```{r corr-env, fig.width=9, fig.height=3.2} corr_env_abund_plot( table = table_meta, metadata = metadata_meta, env_vars = env_vars_meta, taxonomy_db = "Kraken2", level = "phylum", save_table = FALSE ) ``` ### Constrained ordination (CCA) ```{r cca, fig.width=8, fig.height=6} cca_rda_biplot( table = table_meta, metadata = metadata_meta, env_vars = c("pH", "MO", "N", "P", "K"), analysis = "CCA", show_all_env_vectors = TRUE, group_col = "Polygon", scale_arrows = 3 ) ``` ## References
## Session info ```{r session} sessionInfo() ```