### Load Example Analysis Libraries Source: https://github.com/david-barnett/microviz/blob/main/README.md Loads necessary libraries for performing example analyses with microViz and phyloseq. ```r library(phyloseq) library(dplyr) library(ggplot2) ``` -------------------------------- ### Install microViz from R Universe Source: https://github.com/david-barnett/microviz/blob/main/README.md Installs the microViz package from the R Universe repository. This is the recommended installation method. ```r install.packages( "microViz", repos = c(davidbarnett = "https://david-barnett.r-universe.dev", getOption("repos")) ) ``` -------------------------------- ### Install microViz from GitHub Source: https://github.com/david-barnett/microviz/blob/main/README.md Installs the latest development version of microViz directly from GitHub. Requires the 'remotes' package and RTools for Windows users. ```r # Installing from GitHub requires the remotes package install.packages("remotes") # Windows users will also need to have RTools installed! http://jtleek.com/modules/01_DataScientistToolbox/02_10_rtools/ # To install the latest version: remotes::install_github("david-barnett/microViz") ``` -------------------------------- ### Install Bioconductor Dependencies Source: https://github.com/david-barnett/microviz/blob/main/README.md Installs essential Bioconductor packages required for microViz. Run this before installing microViz itself. ```r if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install(c("phyloseq", "microbiome", "ComplexHeatmap"), update = FALSE) ``` -------------------------------- ### Install Specific GitHub Release Source: https://github.com/david-barnett/microviz/blob/main/README.md Use this command to install a specific release version of the microViz package from GitHub. ```r remotes::install_github("david-barnett/microViz@0.13.0") ``` -------------------------------- ### Initialize Ordination Exploration with Dietswap Data Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Initializes ordination exploration using the 'dietswap' dataset. This setup is suitable for general exploration where specific constraints are not yet defined. ```R ord_explore_init(dietswap) ``` -------------------------------- ### Install Suggested CRAN Packages Source: https://github.com/david-barnett/microviz/blob/main/README.md Installs optional CRAN packages that enhance microViz functionality, such as for rotated labels, interactive plots, and modeling. ```r install.packages("ggtext") # for rotated labels on ord_plot() install.packages("ggraph") # for taxatree_plots() install.packages("DT") # for tax_fix_interactive() install.packages("corncob") # for beta binomial models in tax_model() ``` -------------------------------- ### Tax Transform Maaslin2 Default Chaining Example Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/tax_transform.md Demonstrates the output of tax_transform with 'maaslin2-default' chaining, showing the resulting phyloseq object and its properties. ```R ord ``` -------------------------------- ### Initialize Ordination Exploration with Esophagus Data Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Initializes ordination exploration using the 'esophagus' dataset. This example demonstrates handling datasets that may require imputation or validation of sample data and taxonomy tables. ```R ord_explore_init(esophagus) ``` -------------------------------- ### Get all ordination choices Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Retrieves all available unconstrained ordination methods. This is typically used to see the full range of options before selecting a specific method. ```R cat(type) cat(ord_choices(type)) ``` -------------------------------- ### Load microViz Package Source: https://github.com/david-barnett/microviz/blob/main/README.md Loads the microViz package. Ensure you have the package installed before running this command. This message indicates the loaded version and provides helpful links. ```r library(microViz) #> microViz version 0.13.0 - Copyright (C) 2021-2026 David Barnett #> ! Website: https://david-barnett.github.io/microViz #> ✔ Useful? For citation details, run: `citation("microViz")` #> ✖ Silence? `suppressPackageStartupMessages(library(microViz))` ``` -------------------------------- ### Build Ordination with Bray-Curtis Distance Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Use `ord_build` to construct ordinations. This example uses Bray-Curtis distance and PCoA method with identity transformation. ```R ord_build(data = dietswap, rank = "Genus", trans = "identity", dist = "bray", method = "PCoA", constraints = NULL, conditions = NULL) ``` -------------------------------- ### GNU GPL Notice for Interactive Terminal Programs Source: https://github.com/david-barnett/microviz/blob/main/LICENSE.md Display this short notice when a program starts in interactive mode. It informs users about the program's copyright, lack of warranty, and free software status. ```text Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free software, and you are welcome to redistribute it under certain conditions; type 'show c' for details. ``` -------------------------------- ### Dendrogram Structure Example Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/heatmaps.md This example shows a typical dendrogram structure with nested branches and leaf nodes representing samples. It is useful for understanding the output of hierarchical clustering. ```text | | | |--[dendrogram w/ 2 branches and 2 members at h = 1.94] | | | | |--leaf "Sample-138" | | | | `--leaf "Sample-139" | | | `--leaf "Sample-70" | | `--leaf "Sample-68" | `--[dendrogram w/ 2 branches and 2 members at h = 5.12] | |--leaf "Sample-117" | `--leaf "Sample-166" `--[dendrogram w/ 2 branches and 6 members at h = 6.27] |--[dendrogram w/ 2 branches and 4 members at h = 4.93] | |--leaf "Sample-186" | `--[dendrogram w/ 2 branches and 3 members at h = 3.18] | |--[dendrogram w/ 2 branches and 2 members at h = 2.18] | | |--leaf "Sample-172" | | `--leaf "Sample-176" | `--leaf "Sample-170" `--[dendrogram w/ 2 branches and 2 members at h = 3.85] |--leaf "Sample-158" `--leaf "Sample-180" ``` -------------------------------- ### Display Default Tax Fix Prompt Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/tax_agg.md Prints the default prompt message for the `tax_fix` function, guiding users on how to address taxonomic problems. ```r cat(taxFixPrompt()) ``` -------------------------------- ### Get distance choices for esophagus tree type Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Demonstrates `dist_choices` with `type = "tree"` on the esophagus dataset. Shows available generalized UniFrac, weighted UniFrac, unweighted UniFrac, and dpcoa distance metrics. ```R dist_choices(esophagus, type = "tree") ``` -------------------------------- ### Standard GNU GPL Notice for Source Files Source: https://github.com/david-barnett/microviz/blob/main/LICENSE.md Include this notice at the beginning of each source file to state the copyright and licensing terms. It ensures the program remains free software under the GNU GPL. ```text Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` -------------------------------- ### List Sample Variables in Phyloseq Object Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore-shinytest2.md This command lists all available sample variables (metadata columns) within a phyloseq object. Ensure the phyloseq package is loaded. ```R phyloseq::sample_variables(ps) ``` -------------------------------- ### Launch Interactive Shiny Ordination Explorer Source: https://context7.com/david-barnett/microviz/llms.txt Launches a Shiny app for interactive exploration of ordination plots and microbiome compositions. Can accept a raw phyloseq object or a pre-computed ordination. ```r library(microViz) # Pass a raw phyloseq and the app will guide you through building an ordination data(ibd, package = "microViz") pseq <- ibd |> tax_fix() |> phyloseq_validate() ord_explore(pseq) # Or pass a pre-computed ordination to start immediately from the plot library(microbiome) data("dietswap") pre_ord <- dietswap | tax_fix() | tax_transform("clr", rank = "Genus") | ord_calc() ord_explore(pre_ord) ``` -------------------------------- ### Calculate Ordination Distance Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Use `ord_code_dist` to specify distance calculations for ordination. Accepts 'aitchison' and 'none' as examples. ```R cat(ord_code_dist("aitchison")) ``` ```R cat(ord_code_dist("none")) ``` -------------------------------- ### Explore Ordination with Shiny App Source: https://github.com/david-barnett/microviz/blob/main/README.md Launches an interactive Shiny app for exploring ordination results of a phyloseq object. Requires a validated phyloseq object. ```r ord_explore(pseq) # gif generated with microViz version 0.7.4 (plays at 1.75x speed) ``` -------------------------------- ### List Sample Names in Phyloseq Object Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore-shinytest2.md This command lists all sample names (identifiers) present in a phyloseq object. Ensure the phyloseq package is loaded. ```R phyloseq::sample_names(ps) ``` -------------------------------- ### ord_plot vec_tax_all() Arrow Styles Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_arrows.md Use `vec_tax_all()` to get default arrow styling parameters. This function returns linewidth, alpha, and arrow properties. ```r vec_tax_all() ``` -------------------------------- ### Extract Data from Default Aitchison Plot Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_plot.md Extracts the first 50 absolute values from the first column of data for a default Aitchison plot. This is similar to the first example but for a default configuration. ```r cat(abs(p5$data[1:50, 1, drop = TRUE])) ``` -------------------------------- ### Prepare Phyloseq Object for Exploration Source: https://github.com/david-barnett/microviz/blob/main/README.md Prepares a phyloseq object for use with microViz functions. It first fixes taxonomic names and then validates the object. ```r # example data from corncob package pseq <- microViz::ibd %>% tax_fix() %>% phyloseq_validate() ``` -------------------------------- ### ord_plot vec_constraint() Arrow Styles Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_arrows.md Use `vec_constraint()` to get constrained arrow styling parameters. This function returns detailed properties including angle, length, ends, type, colour, lineend, and linejoin. ```r vec_constraint() ``` -------------------------------- ### ord_explore Source: https://context7.com/david-barnett/microviz/llms.txt Launches an interactive Shiny app for exploring ordination plots and inspecting sample compositions. It can accept a raw phyloseq object or a pre-computed ordination. ```APIDOC ## ord_explore — Interactive Shiny ordination explorer Launches a Shiny app that lets users point-and-click to explore ordination plots and inspect the microbiome compositions of selected samples via stacked bar plots, all without writing additional code. ### Usage ```r library(microViz) # Pass a raw phyloseq and the app will guide you through building an ordination data(ibd, package = "microViz") pseq <- ibd |> tax_fix() |> phyloseq_validate() ord_explore(pseq) # Or pass a pre-computed ordination to start immediately from the plot library(microbiome) data("dietswap") pre_ord <- dietswap | tax_fix() | tax_transform("clr", rank = "Genus") | ord_calc() ord_explore(pre_ord) ``` ``` -------------------------------- ### Initialize Ordination Exploration with Custom Ordination Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Initializes ordination exploration with a pre-defined ordination object 'ord'. This is useful when you have already performed a specific ordination (e.g., RDA) and want to explore it further. ```R ord_explore_init(ord) ``` -------------------------------- ### Get distance choices for tree type Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Illustrates the use of `dist_choices` with the `type = "tree"` argument. Returns an empty character vector when no specific tree-based distance metrics are available for the given data. ```R dist_choices(dietswap, type = "tree") ``` -------------------------------- ### Compositional Sample-Taxon Heatmap with Annotations Source: https://context7.com/david-barnett/microviz/llms.txt Displays a sample-by-taxon heatmap of microbial abundances with optional sample and taxon annotations, seriation-based ordering, and ComplexHeatmap customization. ```r library(microViz) data("dietswap", package = "microbiome") htmp <- dietswap | ps_mutate(nationality = as.character(nationality)) | tax_transform("log2", add = 1, chain = TRUE) | comp_heatmap( taxa = tax_top(dietswap, n = 30), name = "Log2(counts+1)", grid_col = NA, colors = heat_palette(palette = viridis::turbo(11)), row_names_side = "left", sample_side = "bottom", sample_anno = sampleAnnotation( Nationality = anno_sample_cat( var = "nationality", col = c(AAM = "grey35", AFR = "grey85"), legend_title = "Nationality" ) ) ) ComplexHeatmap::draw( htmp, annotation_legend_list = attr(htmp, "AnnoLegends"), merge_legends = TRUE ) ``` -------------------------------- ### Ordination Calculation and Plotting with ord_plot Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Demonstrates a typical workflow using the phyloseq object, tax_transform, ord_calc, and ord_plot for ordination analysis and visualization. This includes setting constraints, transformation methods, and plot aesthetics. ```R your_phyloseq %>% tax_transform(rank = "Genus", trans = "identity") %>% ord_calc( constraints = c("test1", "test2"), method = "RDA" ) %>% ord_plot( axes = c(1, 2), plot_taxa = 1:6, colour = "v", fill = "v", shape = "var", alpha = "aVariable", size = 1 ) ``` -------------------------------- ### Prepare DietSwap Data for Analysis Source: https://github.com/david-barnett/microviz/blob/main/README.md Loads the DietSwap dataset and mutates it to include numerical variables for 'weight', 'female', and 'african' status. It also introduces missing values to demonstrate handling of NA data. ```r # get some example data data("dietswap", package = "microbiome") # create a couple of numerical variables to use as constraints or conditions dietswap <- dietswap %>% ps_mutate( weight = recode(bmi_group, obese = 3, overweight = 2, lean = 1), female = if_else(sex == "female", true = 1, false = 0), african = if_else(nationality == "AFR", true = 1, false = 0) ) # add a couple of missing values to show how microViz handles missing data sample_data(dietswap)$african[c(3, 4)] <- NA ``` -------------------------------- ### Explore Palettes by Genus Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Visualize microbial taxa at the 'Genus' level using default color palettes. This helps in understanding the distribution and coloring of individual genera. ```R ord_explore_palet_fun(dietswap, "Genus") ``` -------------------------------- ### Run tax_fix_interactive() with dietswap Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/tax_fix_interactive.md Demonstrates the execution of the tax_fix_interactive() function using the 'dietswap' dataset. This function is used for interactive tax fixing and returns a phyloseq object. ```R tax_fix_interactive( dietswap, "tax_fix_interactive()" ) ``` -------------------------------- ### Heatmap Matrix Parameters Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/heatmaps.md Displays the default parameters for a heatmap matrix, including row and column clustering, spacing, and graphical properties. ```R p@matrix_param ``` -------------------------------- ### Constrained Partial Ordination Source: https://github.com/david-barnett/microviz/blob/main/README.md Performs PERMANOVA with multiple variables and visualizes the results using constrained ordination. This allows for visualizing the effect of specific variables on sample composition while accounting for conditions. Ensure 'aitchison_dists' is available. ```r perm2 <- aitchison_dists %>% dist_permanova(variables = c("weight", "african", "sex"), seed = 321) #> Dropping samples with missings: 2 #> 2026-01-27 13:26:12.777723 - Starting PERMANOVA with 999 perms with 1 processes #> 2026-01-27 13:26:14.066681 - Finished PERMANOVA ``` ```r perm2 %>% ord_calc(constraints = c("weight", "african"), conditions = "female") %>% ord_plot( colour = "nationality", size = 2.5, alpha = 0.35, auto_caption = 7, constraint_vec_length = 1, constraint_vec_style = vec_constraint(1.5, colour = "grey15"), constraint_lab_style = constraint_lab_style( max_angle = 90, size = 3, aspect_ratio = 0.8, colour = "black" ) ) + stat_ellipse(aes(colour = nationality), linewidth = 0.2) + scale_color_brewer(palette = "Set1", guide = guide_legend(position = "inside")) + coord_fixed(ratio = 0.8, clip = "off", xlim = c(-4, 4)) + theme(legend.position.inside = c(0.9, 0.1), legend.background = element_rect()) #> #> Centering (mean) and scaling (sd) the constraints and/or conditions: #> weight #> african #> female ``` -------------------------------- ### Display First 50 Data Points of First Column Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_plot.md This snippet shows how to display the first 50 data points from the first column of the PCA data. It's useful for a quick inspection of the raw data. ```r cat(p6$data[1:50, 1, drop = TRUE]) ``` -------------------------------- ### Aggregate Taxa by Phylum using microViz package Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/tax_agg.md Aggregates taxa in the dietswap dataset to the Phylum level using the `tax_agg` function from the microViz package. The `ps_get` function is used to retrieve the processed phyloseq object. `sort_by = "name"` and `add_unique = TRUE` are used for specific output formatting. ```r ps_get(tax_agg(ps = dietswap, level, sort_by = "name", add_unique = TRUE)) ``` -------------------------------- ### ord_code Helper Function Parameters Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Illustrates the parameters of the ord_code helper function, showing how they map to downstream functions like tax_transform, ord_calc, and ord_plot. ```R ord_code(rank = "Genus", trans = "identity", dist = "none", ord = "RDA", const = c, conds = NULL, x = 1, y = 2, colour = "v", fill = "v", shape = "var", alpha = a, size = 1, plot_taxa = p, ellipses = FALSE, chulls = FALSE, paths = NULL) ``` -------------------------------- ### Build Ordination with CLR Transformation and Auto Method Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Use `ord_build` for ordinations with centered log-ratio (CLR) transformation and automatic method selection. Distance is set to NA. ```R ord_build(data = dietswap, rank = "Genus", trans = "clr", dist = NA, method = "auto", constraints = NULL, conditions = NULL) ``` -------------------------------- ### Display R Session Information Source: https://github.com/david-barnett/microviz/blob/main/README.md Use this function to display detailed information about the R session, including version, platform, loaded packages, and locale settings. This is useful for debugging and ensuring reproducibility. ```r sessionInfo() #> R version 4.5.2 (2025-10-31) #> Platform: aarch64-apple-darwin20 #> Running under: macOS Sequoia 15.7.3 #> #> Matrix products: default #> BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib #> LAPACK: /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/lib/libRlapack.dylib; LAPACK version 3.12.1 #> #> locale: #> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 #> #> time zone: Europe/Amsterdam #> tzcode source: internal #> #> attached base packages: #> [1] stats graphics grDevices utils datasets methods base #> #> other attached packages: #> [1] ggplot2_4.0.1 dplyr_1.1.4 phyloseq_1.54.0 microViz_0.13.0 #> [5] testthat_3.3.2 devtools_2.4.6 usethis_3.2.1 #> #> loaded via a namespace (and not attached): #> [1] gridExtra_2.3 remotes_2.5.0 permute_0.9-8 #> [4] rlang_1.1.7 magrittr_2.0.4 clue_0.3-66 #> [7] GetoptLong_1.1.0 ade4_1.7-23 otel_0.2.0 #> [10] matrixStats_1.5.0 compiler_4.5.2 mgcv_1.9-3 #> [13] png_0.1-8 vctrs_0.7.1 reshape2_1.4.5 #> [16] stringr_1.6.0 pkgconfig_2.0.3 shape_1.4.6.1 #> [19] crayon_1.5.3 fastmap_1.2.0 magick_2.8.6 #> [22] XVector_0.50.0 ellipsis_0.3.2 labeling_0.4.3 #> [25] ca_0.71.1 rmarkdown_2.30 markdown_2.0 #> [28] sessioninfo_1.2.3 purrr_1.2.1 xfun_0.56 #> [31] cachem_1.1.0 litedown_0.7 jsonlite_2.0.0 #> [34] biomformat_1.38.0 rhdf5filters_1.22.0 Rhdf5lib_1.32.0 #> [37] parallel_4.5.2 cluster_2.1.8.1 R6_2.6.1 #> [40] stringi_1.8.7 RColorBrewer_1.1-3 pkgload_1.4.1 #> [43] brio_1.1.5 Rcpp_1.1.1 Seqinfo_1.0.0 #> [46] iterators_1.0.14 knitr_1.51 IRanges_2.44.0 #> [49] Matrix_1.7-4 splines_4.5.2 igraph_2.2.1 #> [52] tidyselect_1.2.1 rstudioapi_0.17.1 yaml_2.3.12 #> [55] viridis_0.6.5 vegan_2.7-2 TSP_1.2.6 #> [58] ggtext_0.1.2 doParallel_1.0.17 codetools_0.2-20 #> [61] pkgbuild_1.4.8 lattice_0.22-7 tibble_3.3.1 #> [64] plyr_1.8.9 Biobase_2.70.0 withr_3.0.2 #> [67] S7_0.2.1 evaluate_1.0.5 Rtsne_0.17 #> [70] survival_3.8-3 xml2_1.3.8 circlize_0.4.17 #> [73] Biostrings_2.78.0 pillar_1.11.1 foreach_1.5.2 #> [76] stats4_4.5.2 generics_0.1.4 S4Vectors_0.48.0 #> [79] microbiome_1.32.0 commonmark_2.0.0 scales_1.4.0 #> [82] glue_1.8.0 tools_4.5.2 data.table_1.18.0 #> [85] registry_0.5-1 fs_1.6.6 rhdf5_2.54.1 #> [88] grid_4.5.2 Cairo_1.6-2 tidyr_1.3.2 #> [91] ape_5.8-1 seriation_1.5.8 colorspace_2.1-2 #> [94] nlme_3.1-168 cli_3.6.5 viridisLite_0.4.2 #> [97] ComplexHeatmap_2.26.0 gtable_0.3.6 digest_0.6.39 #> [100] BiocGenerics_0.56.0 rjson_0.2.23 farver_2.1.2 #> [103] memoise_2.0.1 htmltools_0.5.9 multtest_2.66.0 #> [106] lifecycle_1.0.5 GlobalOptions_0.1.3 gridtext_0.1.5 #> [109] MASS_7.3-65 ``` -------------------------------- ### Matrix Parameters for Heatmap Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/heatmaps.md Displays the parameters related to the matrix of a heatmap, such as row and column clustering, and gaps. ```R p@matrix_param[names(p@matrix_param) != "cell_fun"] ``` -------------------------------- ### Calculate Ordinations with ord_calc Source: https://context7.com/david-barnett/microviz/llms.txt Computes ordinations (PCA, PCoA, RDA, CAP, CCA, NMDS) and stores them in a psExtra object. Automatically infers the method based on data type (transformed data or distance matrix) and supports constrained analyses. ```r library(phyloseq) library(microViz) data("dietswap", package = "microbiome") dietswap <- ps_mutate( dietswap, weight = dplyr::recode(bmi_group, obese = 3, overweight = 2, lean = 1), female = dplyr::if_else(sex == "female", 1L, 0L) ) # Unconstrained Aitchison PCA (auto-detected because no distance, no constraints) pca_obj <- dietswap |> tax_transform("clr", rank = "Genus") |> ord_calc() # method = "auto" --> PCA # Constrained CAP with Bray-Curtis distances cap_obj <- dietswap |> tax_agg("Genus") |> dist_calc("bray") |> ord_calc(constraints = c("weight", "female")) # Partial RDA: constrained by weight and nationality, sex partialled out rda_obj <- dietswap |> tax_transform("clr", rank = "Genus") |> ord_calc( constraints = c("weight", "african"), conditions = "female" ) ``` -------------------------------- ### Generate Compositional Heatmap Source: https://github.com/david-barnett/microviz/blob/main/README.md Creates a compositional heatmap of the top 30 taxa, using log2 transformation and custom annotations for nationality. The heatmap displays microbial composition across samples, with dendrograms for rows and samples. ```r htmp <- dietswap %>% ps_mutate(nationality = as.character(nationality)) %>% tax_transform("log2", add = 1, chain = TRUE) %>% comp_heatmap( taxa = tax_top(dietswap, n = 30), grid_col = NA, name = "Log2p", taxon_renamer = function(x) stringr::str_remove(x, " [ae]t rel."), colors = heat_palette(palette = viridis::turbo(11)), row_names_side = "left", row_dend_side = "right", sample_side = "bottom", sample_anno = sampleAnnotation( Nationality = anno_sample_cat( var = "nationality", col = c(AAM = "grey35", AFR = "grey85"), box_col = NA, legend_title = "Nationality", size = grid::unit(4, "mm") ) ) ) ComplexHeatmap::draw( object = htmp, annotation_legend_list = attr(htmp, "AnnoLegends"), merge_legends = TRUE ) ``` -------------------------------- ### Heatmap Matrix Parameters Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/heatmaps.md Displays the parameters controlling the heatmap matrix, such as clustering, gaps, and jitter. Useful for understanding the structural and visual properties of the heatmap grid. ```R v@matrix_param[names(v@matrix_param) != "cell_fun"] ``` -------------------------------- ### Display First 50 Data Points of Second Column Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_plot.md This snippet displays the first 50 data points from the second column of the PCA data. This is helpful for examining the distribution and values in the second principal component. ```r cat(p6$data[1:50, 2, drop = TRUE]) ``` -------------------------------- ### Linear Model Output for Birthweight Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/taxatree_models2stats.md Displays the output of a linear model applied to birthweight data, aggregated at the genus level. Shows the resulting phyloseq object with extra slots and the generated tax_stats dataframe. ```R lmBirthweight_psx ``` -------------------------------- ### Create Compositional Bar Plot Source: https://github.com/david-barnett/microviz/blob/main/README.md Generates a compositional bar plot visualizing microbial taxa abundance at the genus level, faceted by nationality. Includes custom renaming, palette, and theme adjustments for clarity. ```r dietswap %>% comp_barplot( tax_level = "Genus", n_taxa = 15, other_name = "Other", taxon_renamer = function(x) stringr::str_remove(x, " [ae]t rel."), palette = distinct_palette(n = 15, add = "grey90"), merge_other = FALSE, bar_outline_colour = "darkgrey" ) + coord_flip() + facet_wrap("nationality", nrow = 1, scales = "free") + labs(x = NULL, y = NULL) + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank()) ``` -------------------------------- ### Display Tax Fix Prompt with Unknowns Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/tax_agg.md Prints a customized prompt message for the `tax_fix` function, including specific unknown taxa that need to be addressed. ```r cat(taxFixPrompt(unknowns = c("anUnknown", "another"))) ``` -------------------------------- ### Perform PERMANOVA Analysis Source: https://github.com/david-barnett/microviz/blob/main/README.md Calculates Aitchison distances and performs a PERMANOVA test to assess the significance of 'bmi_group' on microbial composition. Ensure 'dietswap' data is loaded and appropriate transformation/distance calculation functions are available. For stable p-values, use at least 999 permutations. ```r # calculate distances aitchison_dists <- dietswap %>% tax_transform("identity", rank = "Family") %>% dist_calc("aitchison") # the more permutations you request, the longer it takes # but also the more stable and precise your p-values become aitchison_perm <- aitchison_dists %>% dist_permanova( seed = 1234, # for set.seed to ensure reproducibility of random process n_processes = 1, n_perms = 99, # you should use at least 999! variables = "bmi_group" ) #> 2026-01-27 13:26:12.735146 - Starting PERMANOVA with 99 perms with 1 processes #> 2026-01-27 13:26:12.765247 - Finished PERMANOVA # view the permanova results perm_get(aitchison_perm) %>% as.data.frame() #> Df SumOfSqs R2 F Pr(>F) #> bmi_group 2 89.70978 0.03760034 4.278095 0.01 #> Residual 219 2296.16703 0.96239966 NA NA #> Total 221 2385.87681 1.00000000 NA NA # view the info stored about the distance calculation info_get(aitchison_perm) #> psExtra info: #> tax_agg = "Family" tax_trans = "identity" dist_method = "aitchison" ``` -------------------------------- ### Basic PCA Plot with Taxa Loading Arrows and BMI Group Ellipses Source: https://context7.com/david-barnett/microviz/llms.txt Generates a Principal Component Analysis (PCA) plot, visualizing the top 5 taxa loadings as arrows and highlighting BMI groups with ellipses. Requires pre-computed ordination data. ```r pca |> ord_plot( colour = "bmi_group", plot_taxa = 1:5, size = 2, auto_caption = 8 ) + stat_ellipse(aes(colour = bmi_group), linetype = 2) + scale_colour_brewer(palette = "Set1") + coord_fixed() ``` -------------------------------- ### Compositional Stacked Bar Plot with Grouping and Faceting Source: https://context7.com/david-barnett/microviz/llms.txt Generates stacked bar charts of sample compositions, automatically converting to proportions and selecting top taxa. Supports grouping and faceting for comparative analysis. ```r library(ggplot2) library(microViz) data("dietswap", package = "microbiome") # Top-15 genera, samples grouped by nationality, horizontal bars dietswap |> tax_fix() | comp_barplot( tax_level = "Genus", n_taxa = 15, other_name = "Other", palette = distinct_palette(n = 15, add = "grey90"), bar_outline_colour = "darkgrey", merge_other = FALSE ) + coord_flip() + facet_wrap("nationality", nrow = 1, scales = "free") + labs(x = NULL, y = NULL) + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank()) ``` ```r # Grouped output: one plot per nationality (returns a list of ggplots) plot_list <- dietswap | tax_fix() | comp_barplot(tax_level = "Genus", n_taxa = 10, group_by = "nationality") patchwork::wrap_plots(plot_list, ncol = 2) ``` -------------------------------- ### Calculate Distance Matrices with dist_calc Source: https://context7.com/david-barnett/microviz/llms.txt Computes pairwise distance matrices from phyloseq/psExtra objects. Supports various distance metrics including Bray-Curtis and Aitchison. Requires a phylogenetic tree for UniFrac distances. ```r library(microViz) data("dietswap", package = "microbiome") # Bray-Curtis dissimilarity at Genus level bc_dist <- dietswap |> tax_agg("Genus") |> dist_calc("bray") dist_get(bc_dist) # retrieve the dist object # Aitchison distance (CLR + Euclidean); no prior transformation needed ait_dist <- dietswap |> tax_agg("Genus") |> dist_calc("aitchison") # UniFrac distances (require a phylogenetic tree in the phyloseq object) data("esophagus", package = "phyloseq") guf_dist <- esophagus |> dist_calc("gunifrac") |u003E # generalised UniFrac (alpha = 0.5 by default) dist_get() ``` -------------------------------- ### Interactive PCA Plot with Selectable Points Source: https://context7.com/david-barnett/microviz/llms.txt Creates an interactive PCA plot where points can be selected in the browser. Requires the ggiraph package for interactivity. The 'data_id' argument links plot points to sample identifiers. ```r library(ggiraph) interactive_p <- pca | ord_plot(colour = "bmi_group", interactive = TRUE, data_id = "sample") girafe(ggobj = interactive_p) ``` -------------------------------- ### Generate Correlation Heatmap Source: https://github.com/david-barnett/microviz/blob/main/README.md Creates a correlation heatmap annotated with taxa prevalence and abundance. This involves data preprocessing, including mutation of numerical variables, filtering taxa, and transformation. Ensure 'dietswap' data is loaded and necessary functions like 'ps_mutate', 'tax_filter', 'tax_transform', and 'cor_heatmap' are available. ```r # set up the data with numerical variables and filter to top taxa psq <- dietswap %>% ps_mutate( weight = recode(bmi_group, obese = 3, overweight = 2, lean = 1), female = if_else(sex == "female", true = 1, false = 0), african = if_else(nationality == "AFR", true = 1, false = 0) ) %>% tax_filter( tax_level = "Genus", min_prevalence = 1 / 10, min_sample_abundance = 1 / 10 ) %>% tax_transform("identity", rank = "Genus") #> Proportional min_prevalence given: 0.1 --> min 23/222 samples. # randomly select 30 taxa from the 50 most abundant taxa (just for an example) set.seed(123) taxa <- sample(tax_top(psq, n = 50), size = 30) # actually draw the heatmap cor_heatmap( data = psq, taxa = taxa, taxon_renamer = function(x) stringr::str_remove(x, " [ae]t rel."), tax_anno = taxAnnotation( Prev. = anno_tax_prev(undetected = 50), Log2 = anno_tax_box(undetected = 50, trans = "log2", zero_replace = 1) ) ) ``` -------------------------------- ### ord_calc Source: https://context7.com/david-barnett/microviz/llms.txt Calculates various ordination methods (PCA, PCoA, RDA, CAP, CCA, NMDS) from phyloseq/psExtra objects, supporting both unconstrained and constrained analyses. ```APIDOC ## `ord_calc` — Calculate ordinations (PCA, PCoA, RDA, CAP, CCA, NMDS) Computes an ordination from a `psExtra` object and stores the result back in it. Uses `method = "auto"` to infer the appropriate method (PCA/RDA for transformed data, PCoA/CAP when a distance matrix is present). Supports constrained and partially constrained (conditioned) analyses. ```r library(phyloseq) library(microViz) data("dietswap", package = "microbiome") dietswap <- ps_mutate( dietswap, weight = dplyr::recode(bmi_group, obese = 3, overweight = 2, lean = 1), female = dplyr::if_else(sex == "female", 1L, 0L) ) # Unconstrained Aitchison PCA (auto-detected because no distance, no constraints) pca_obj <- dietswap |> tax_transform("clr", rank = "Genus") |> ord_calc() # method = "auto" --> PCA # Constrained CAP with Bray-Curtis distances cap_obj <- dietswap |> tax_agg("Genus") |> dist_calc("bray") |> ord_calc(constraints = c("weight", "female")) # Partial RDA: constrained by weight and nationality, sex partialled out rda_obj <- dietswap |> tax_transform("clr", rank = "Genus") |> ord_calc( constraints = c("weight", "african"), conditions = "female" ) ``` ``` -------------------------------- ### Load Dietswap Data Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/tax_agg.md Loads the dietswap dataset, which is a phyloseq object containing microbiome data. ```r dietswap ``` -------------------------------- ### Inspect Phyloseq Object Structure Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore-shinytest2.md Use this to view the structure and components of a phyloseq object. It displays the dimensions and types of the OTU table, sample data, taxonomy table, and phylogenetic tree. ```R ps ``` -------------------------------- ### Explore Palettes by Family with Custom Color Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Visualize microbial taxa at the 'Family' level, sorted by median abundance, and using a custom color 'colourz' for unassigned or 'Other' categories. This is useful for highlighting specific taxonomic groups or custom color schemes. ```R ord_explore_palet_fun(ps = dietswap, tax_level = "Family", top_by = median, other = "colourz") ``` -------------------------------- ### Basic Ordination Plot with ord_code Source: https://github.com/david-barnett/microviz/blob/main/tests/testthat/_snaps/ord_explore.md Generates a basic ordination plot using RDA method without constraints. This is useful for initial exploration of community structure. ```R ord_code(rank = "Genus", trans = "identity", dist = "none", ord = "RDA", const = c, conds = NULL, x = 1, y = 2, colour = "v", fill = "v", shape = "var", alpha = a, size = 1, plot_taxa = p, ellipses = FALSE, chulls = FALSE, paths = NULL) ``` ```R your_phyloseq %>% tax_transform(rank = "Genus", trans = "identity") %>% ord_calc( method = "RDA" ) %>% ord_plot( axes = c(1, 2), colour = "v", fill = "v", shape = "var", alpha = 0.5, size = 1 ) ``` -------------------------------- ### comp_heatmap Source: https://context7.com/david-barnett/microviz/llms.txt Displays a sample × taxon heatmap of microbial abundances with customizable annotations and ordering. It leverages the ComplexHeatmap API for extensive customization. ```APIDOC ## comp_heatmap — Compositional sample–taxon heatmap Displays a sample × taxon heatmap of (transformed) microbial abundances, with optional sample and taxon annotation tracks, seriation-based ordering, and the full ComplexHeatmap customisation API. ### Usage ```r library(microViz) data("dietswap", package = "microbiome") htmp <- dietswap | ps_mutate(nationality = as.character(nationality)) | tax_transform("log2", add = 1, chain = TRUE) | comp_heatmap( taxa = tax_top(dietswap, n = 30), name = "Log2(counts+1)", grid_col = NA, colors = heat_palette(palette = viridis::turbo(11)), row_names_side = "left", sample_side = "bottom", sample_anno = sampleAnnotation( Nationality = anno_sample_cat( var = "nationality", col = c(AAM = "grey35", AFR = "grey85"), legend_title = "Nationality" ) ) ) ComplexHeatmap::draw( htmp, annotation_legend_list = attr(htmp, "AnnoLegends"), merge_legends = TRUE ) ``` ```