Package 'MicroBioMeta'

Title: Analysis and Visualization of Microbiome Diversity, Composition, and Differential Abundance
Description: The goal of MicroBioMeta is to support beginners in microbiome data analysis, whether working with metagenomic or metabarcoding datasets. It enables users with limited experience in R to explore, visualize, and analyze results with minimal coding and customization. This helps save time on scripting, while still producing statistically robust results and publication-ready figures in an intuitive and accessible way.
Authors: Stephanie Hereira Pacheco [aut, cre] (ORCID: <https://orcid.org/0000-0003-1433-8187>), Nina Montoya Ciriaco [aut] (ORCID: <https://orcid.org/0009-0000-3555-0692>), Karla Zarco González [aut] (ORCID: <https://orcid.org/0009-0003-3407-9036>)
Maintainer: Stephanie Hereira Pacheco <[email protected]>
License: Artistic-2.0
Version: 0.99.0
Built: 2026-11-20 23:03:21 UTC
Source: https://github.com/BiocStaging/MicroBioMeta

Help Index


Relative abundance barplot

Description

Generates a bar plot of relative abundance (%) for the most abundant taxa groups across samples or sample groups.

Usage

abundance_bar_plot(
  table,
  metadata = NULL,
  taxonomy_db = "silva",
  level = "genus",
  x_col = NULL,
  facet_by = NULL,
  width_equal = FALSE,
  label = "taxonomy",
  top_n = 15,
  x_axis_title = "Samples",
  y_axis_title = "Relative abundance (%)",
  x_label_angle = 0,
  strip_text_bold = FALSE,
  strip_color = "grey",
  palette = "default",
  taxa_colors = NULL,
  taxa_order = "ascending",
  aspect_ratio = NULL,
  add_remained = FALSE,
  save_table = FALSE,
  table_filename = "relative_abundance.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table). Optional: if NULL (default), one bar is drawn per sample.

taxonomy_db

Character. Database the taxonomy strings come from: "silva" (default), "gg2" (Greengenes2, also "gg"), "unite" or "Kraken2" (also "kraken"). Case-insensitive.

level

Character. Taxonomic level: "kingdom", "phylum", "class", "order", "family", "genus" (default) or "species". Case-insensitive.

x_col

Character. Name of the column in metadata for the x-axis. If NULL (default), one bar per sample.

facet_by

Character. Name of the column in metadata to facet the plot by. Optional; NULL (default) for no facets.

width_equal

Logical. If TRUE, all bars have equal width regardless of sample count per group. Default FALSE.

label

Character. Title of the taxa legend. Default "taxonomy".

top_n

Integer. Number of most abundant taxa to show. Default 15.

x_axis_title

Character. Title of the x-axis. Default "Samples".

y_axis_title

Character. Title of the y-axis. Default "Relative abundance (%)".

x_label_angle

Numeric. Rotation (degrees) of the x-axis labels. Default 0 (horizontal); use 45 or 90 if they overlap.

strip_text_bold

Logical. If TRUE, the facet strip labels are bold. Default FALSE.

strip_color

Character. Background color of the facet strips (used when facet_by is set). Default "grey".

palette

Character. Palette for the taxa: "default" (bright colors, the original MicroBioMeta palette), "brewer" (the qualitative RColorBrewer palettes Accent, Dark2, Paired, Pastel1, Pastel2, Set1, Set2 and Set3 joined, without greys; not colorblind-friendly) or "safe" (colorblind-friendly "Safe" palette, 11 colors; with more taxa the colors are interpolated and are no longer fully colorblind-safe). The most abundant taxon gets the first color. Default "default".

taxa_colors

Optional named character vector of colors, one per taxon (names = taxa as shown in the legend). Taxa not named keep the palette colors. Default NULL.

taxa_order

Character. Order of the taxa in the bars and the legend: "ascending" (default; the most abundant taxon at the bottom of both) or "descending" (the most abundant taxon at the top of both).

aspect_ratio

Numeric. Aspect ratio (height/width) of each panel. Default NULL (automatic).

add_remained

Logical. If TRUE, adds an "Other" category with the sum of the remaining taxa. Default FALSE.

save_table

Logical. If TRUE, saves the relative-abundance table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "relative_abundance.txt".

Details

  • Relative abundances are calculated per sample (%).

  • Taxa are collapsed to the taxonomic level; taxa not resolved to that level are shown as "other ".

  • Only the top top_n taxa are shown; others are filtered out.

  • Samples are grouped and ordered according to x_col.

  • Optional faceting by facet_by if provided.

  • Features assigned only to a kingdom/domain (e.g. "d__Bacteria;__;__;__;__;__") or "Unassigned" are removed.

Value

A ggplot object with the stacked bar plot of relative abundances.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

abundance_bar_plot(
    table = table,
    metadata = metadata,
    taxonomy_db = "silva",
    level = "genus",
    x_col = "Location",
    label = "Genus",
    facet_by = "Treatment",
    top_n = 30,
    add_remained = TRUE
)

Heatmap of relative abundance

Description

Creates a heatmap (with ComplexHeatmap) of the relative abundance of the most abundant features (ASVs, OTUs or taxa).

Usage

abundance_heatmap_plot(
  table,
  metadata = NULL,
  condition1 = NULL,
  condition2 = NULL,
  condition3 = NULL,
  colors_condition1 = NULL,
  colors_condition2 = NULL,
  colors_condition3 = NULL,
  name_legend_condition1 = NULL,
  name_legend_condition2 = NULL,
  name_legend_condition3 = NULL,
  top_n = 15,
  exclude_unclassified = TRUE,
  cluster = TRUE,
  show_column_names = TRUE,
  cell_size = NULL,
  annotation_height = NULL,
  save_table = FALSE,
  table_filename = "abundance_heatmap_table.txt",
  feature_prefix = "",
  max_label_length = 35,
  composite_names = TRUE,
  draw = TRUE
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table). Optional: if NULL (default), the heatmap has no sample annotations.

condition1

Character. Name of the column in metadata for the first column annotation. Optional; NULL (default) for none.

condition2

Character. Name of the column in metadata for the second column annotation. Optional; NULL (default) for none.

condition3

Character. Name of the column in metadata for the third column annotation. Optional; NULL (default) for none.

colors_condition1

Optional character vector of colors for condition1. If named, colors are matched to the values by name (e.g. c(Roots = "#009E73", Rhizosphere = "#56B4E9")); otherwise they are assigned in alphabetical order of the values. If NULL (default), the colorblind-friendly Okabe-Ito palette is used.

colors_condition2

Optional character vector of colors for condition2 (same rules as colors_condition1). If NULL (default), colors of the colorblind-friendly "Safe" palette are used, which contrast with those of condition1.

colors_condition3

Optional character vector of colors for condition3 (same rules as colors_condition1). If NULL (default), a third set of colorblind-friendly colors is used.

name_legend_condition1

Character. Title of the legend of condition1. If NULL (default), the name of condition1 is used.

name_legend_condition2

Character. Title of the legend of condition2. If NULL (default), the name of condition2 is used.

name_legend_condition3

Character. Title of the legend of condition3. If NULL (default), the name of condition3 is used.

top_n

Integer. Number of most abundant features to show. Default 15.

exclude_unclassified

Logical. If TRUE (default), taxa with no classification at any level ("Unclassified") are dropped before selecting the top_n most abundant features, so all the rows are identified taxa. Use FALSE to keep them.

cluster

Logical. If TRUE (default), the rows are clustered; if FALSE, they are ordered by abundance.

show_column_names

Logical. If TRUE (default), the sample names are shown.

cell_size

Numeric. Side, in millimeters, of each (square) cell. If NULL (default), it is set automatically.

annotation_height

Numeric. Height, in millimeters, of each column annotation bar (condition1, condition2, condition3). If NULL (default), the cell height is used.

save_table

Logical. If TRUE, saves the abundance table shown in the heatmap as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "abundance_heatmap_table.txt".

feature_prefix

Character. Prefix of the row labels, before the row number (e.g. feature_prefix = "ASV" labels the rows "ASV1", "ASV2"...). Default "" (rows labeled "1", "2"...).

max_label_length

Integer. Taxon names longer than this many characters are cut with an ellipsis in the row labels. NULL never cuts them. Default 35.

composite_names

Logical. If TRUE (default), SILVA composite names of three or more genera are labeled with the last genus plus "group" (e.g. "Allorhizobium-Neorhizobium-Pararhizobium-Rhizobium" becomes "Rhizobium group"); two-genus names (e.g. "Escherichia-Shigella") are kept whole. The full names are kept in the saved table.

draw

Logical. If TRUE (default), the heatmap is drawn on the current device. Use FALSE to only build the returned grob without drawing it, e.g. to combine it with other plots; then, unless cell_size is given, cells stretch to fill the panel they are placed in instead of having a fixed size.

Value

Invisibly, a gTree (grid grob) with the heatmap of the top_n most abundant features. Printing it (e.g. typing its name) draws the heatmap; it can also be combined with other plots (e.g. cowplot::plot_grid(), patchwork::wrap_elements()).

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)
metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

abundance_heatmap_plot(
    table                  = table,
    metadata               = metadata,
    condition1             = "Location",
    condition2             = "Treatment",
    condition3             = "Plot",
    top_n                  = 50,
    cluster                = TRUE,
    show_column_names      = FALSE,
    name_legend_condition1 = "Location",
    name_legend_condition2 = "Treatment",
    name_legend_condition3 = "Plot"
)

heat <- abundance_heatmap_plot(
    table = table,
    metadata = metadata,
    condition1 = "Location",
    condition2 = "Treatment",
    top_n = 20,
    show_column_names = FALSE,
    colors_condition1 = c(Rhizosphere = "#56B4E9", Roots = "#009E73"),
    colors_condition2 = c(
        Control = "#CC6677",
        Moderate_drought = "#332288",
        Severe_drought = "#999933"
    ),
    name_legend_condition1 = "Compartment",
    feature_prefix = "ASV",
    max_label_length = 30,
    draw = FALSE
)
heat # printing the returned object draws the heatmap

Sankey diagram of relative abundances

Description

Creates an interactive Sankey diagram (with networkD3) of how the relative abundance flows across taxonomic ranks.

Usage

abundance_sankey_plot(
  table,
  output_file = NULL,
  maxn = 25,
  taxRanks = c("D", "K", "P", "C", "O", "F", "G", "S"),
  taxonomy_db = "silva",
  width = NULL,
  height = NULL,
  save_table = FALSE,
  table_filename = "sankey_nodes_links.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

output_file

Character or NULL. Path of an HTML file to save the interactive diagram to. If NULL (default), nothing is written to disk; the diagram is only returned.

maxn

Integer. Maximum number of taxa per rank. Default 25. At each rank the most abundant taxa are chosen among the children of the taxa kept at the previous rank, so every flow follows the hierarchy without skipping columns.

taxRanks

Character vector of the ranks to show, as one-letter codes: "D" (domain), "K" (kingdom), "P", "C", "O", "F", "G" and "S". Default all of them.

taxonomy_db

Character. Database the taxonomy strings come from: "silva" (default), "gg2" (Greengenes2, also "gg"), "unite" or "Kraken2" (also "kraken"). Case-insensitive.

width, height

Numeric or NULL. Width and height of the diagram in pixels. If NULL (default), the widget's default size is used (it fills the available width).

save_table

Logical. If TRUE, saves the Sankey nodes and links (one table, with a table_type column: "node" or "link") as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "sankey_nodes_links.txt".

Value

Invisibly returns the Sankey diagram object (an htmlwidget that is shown when printed). If output_file is given, it is also saved as an HTML file.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

abundance_sankey_plot(
    table        = table,
    output_file  = file.path(tempdir(), "sankey_output.html"),
    maxn         = 10,
    taxRanks     = c("P", "C", "G", "S"),
    taxonomy_db  = "silva"
)

ALDEx2 differential abundance heatmap

Description

Runs ALDEx2 between two groups and shows the differentially abundant taxa as a heatmap (with ComplexHeatmap) of their CLR values, annotated with the effect size and the p-value.

Usage

aldex_heatmap_plot(
  table,
  metadata,
  group_col,
  effect_threshold = 0,
  pval_threshold = 0.05,
  p_adjust_method = "BH",
  mc_samples = 128,
  cluster_rows = FALSE,
  cluster_columns = FALSE,
  heatmap_colors = NULL,
  effect_colors = c("#009E73", "white", "#CC79A7"),
  pvalue_colors = c(`<0.001` = "#000000", `<0.01` = "#D55E00", `<0.05` = "#F0E442",
    `>0.05` = "grey85"),
  group_colors = NULL,
  save_table = FALSE,
  table_filename = "aldex_pval_effect.txt",
  draw = TRUE
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

group_col

Character. Name of the column in metadata that defines the groups. It must have exactly two groups.

effect_threshold

Numeric. Minimum absolute effect size to retain. Default 0 (no effect-size filter), so by default the heatmap shows the same taxa that aldex_volcano_plot colors as significant.

pval_threshold

Numeric or NULL. P-value cutoff (after p_adjust_method) to keep only significant taxa. Default 0.05. If NULL, only effect_threshold is applied.

p_adjust_method

Character. "BH" (default) or "none": use the Benjamini-Hochberg adjusted p-values of ALDEx2 (wi.eBH) or the raw ones (wi.ep) for pval_threshold and the p-value annotation. ALDEx2 only computes the BH correction.

mc_samples

Integer. Number of ALDEx2 Monte Carlo instances. Default 128 (ALDEx2's default), recommended for final analyses. Fewer instances are faster but the p-values and effect sizes are less stable (e.g. 16 for a quick look); call set.seed() before the function to make the result reproducible.

cluster_rows

Logical. Cluster heatmap rows (default FALSE).

cluster_columns

Logical. Cluster heatmap columns (default FALSE).

heatmap_colors

Controls the color scale of the main heatmap body (CLR values). Three options: NULL (default, same as "viridis") uses a sequential colorblind-friendly viridis scale (the same family used in abundance_heatmap_plot), with range computed automatically from the data; a preset name string: "viridis" or one of the diverging presets "BuOr" (blue-orange), "BuVm" (blue-vermillion), "BuPk" (blue-pink), "GnPk" (green-pink); or a circlize::colorRamp2 function for full manual control.

effect_colors

Three colors for the effect size annotation strip: negative, zero and positive effect (mapped to -1.5, 0 and 1.5). Default c("#009E73", "white", "#CC79A7") (green-white-pink, colorblind-friendly, distinct from the heatmap body and p-value defaults). A circlize::colorRamp2() function is also accepted.

pvalue_colors

Named vector of colors for the p-value annotation strip, with names "<0.001", "<0.01", "<0.05" and ">0.05". Default black/vermillion/yellow/grey (distinct from the heatmap body and effect size defaults). A list with one such vector named "p-value" is also accepted.

group_colors

Optional character vector of colors for the group annotation, one per group, named after the groups or in their order. If NULL (default), the colorblind-friendly Okabe-Ito palette is used (orange/blue for two groups).

save_table

Logical. If TRUE, saves the ALDEx2 results of the plotted taxa (effect size, diff.btw and p-value category) as a tab-delimited file. Default FALSE. effect and diff.btw are saved as ALDEx2 returns them (second group in alphabetical order minus the first); the higher_in column says in which group each taxon is higher.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "aldex_pval_effect.txt".

draw

Logical. If TRUE (default), the heatmap is drawn on the current device. Use FALSE to only build the returned grob without drawing it.

Value

Invisibly, a gTree (grid grob) with the heatmap. Printing it (e.g. typing its name) draws the heatmap; it can also be combined with other plots (e.g. cowplot::plot_grid(), patchwork::wrap_elements()).

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

# group_col must have exactly two groups; Location has two
# (Rhizosphere and Roots) in the bundled example data. Here taxa are
# filtered by effect size alone (pval_threshold = NULL), since this small
# (46-sample) dataset has few taxa with significant p-values.
aldex_heatmap_plot(
    table            = table,
    metadata         = metadata,
    group_col        = "Location",
    mc_samples       = 16,
    effect_threshold = 0.5,
    pval_threshold   = NULL
)

# All the colors have colorblind-friendly defaults, but each can be set by
# hand: group_colors (difference bars, named after the groups),
# effect_colors (negative, zero and positive effect size), pvalue_colors
# (one color per p-value class) and heatmap_colors (median clr values)

aldex_heatmap_plot(
    table = table,
    metadata = metadata,
    group_col = "Location",
    mc_samples = 16,
    effect_threshold = 0.5,
    pval_threshold = NULL,
    group_colors = c(Rhizosphere = "#56B4E9", Roots = "#009E73"),
    effect_colors = c("#0072B2", "white", "#E69F00"),
    pvalue_colors = c(
        "<0.001" = "black", "<0.01" = "grey30",
        "<0.05" = "grey60", ">0.05" = "grey90"
    ),
    heatmap_colors = "BuOr"
)

ALDEx2 volcano or effect size plot

Description

Runs ALDEx2 between two groups and plots the results as a volcano plot or an effect size plot.

Usage

aldex_volcano_plot(
  table,
  metadata,
  group_col,
  type = "volcano",
  mc_samples = 128,
  col_inf = "#56B4E9",
  col_sup = "#E69F00",
  threshold_lower = -1.5,
  threshold_upper = 1.5,
  cond = NULL,
  pval_threshold = 0.05,
  p_adjust_method = "BH",
  show_labels = TRUE,
  taxa = NULL,
  x_axis_title = NULL,
  y_axis_title = NULL,
  label_size = 3.5,
  filter_uncultured = FALSE,
  save_table = FALSE,
  table_filename = "aldex_pval_effect.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

group_col

Character. Name of the column in metadata that defines the groups. It must have exactly two groups.

type

Type of plot to generate: "volcano" (default, volcano plot) or "effect" (effect-size plot). Case-insensitive.

mc_samples

Integer. Number of ALDEx2 Monte Carlo instances. Default 128 (ALDEx2's default), recommended for final analyses. Fewer instances are faster but the p-values and effect sizes are less stable (e.g. 16 for a quick look); call set.seed() before the function to make the result reproducible.

col_inf

Character. Color of the taxa lower in cond. Default "#56B4E9" (Okabe-Ito blue).

col_sup

Character. Color of the taxa higher in cond. Default "#E69F00" (Okabe-Ito orange).

threshold_lower

Numeric. Lower cutoff on the x-axis (effect size or difference between groups), drawn as a dashed line. Default -1.5.

threshold_upper

Numeric. Upper cutoff on the x-axis (effect size or difference between groups), drawn as a dashed line. Default 1.5.

cond

Name of the reference condition for the plot labels: positive values on the x-axis mean higher in cond. Default NULL, the condition of the first sample in table.

pval_threshold

Numeric. P-value cutoff (after p_adjust_method), drawn as the dashed horizontal line. Default 0.05.

p_adjust_method

Character. "BH" (default) or "none": use the Benjamini-Hochberg adjusted p-values of ALDEx2 (wi.eBH) or the raw ones (wi.ep) for the y-axis and pval_threshold. ALDEx2 only computes the BH correction.

show_labels

Logical. If TRUE (default), shows the "Higher in"/"Lower in" cond labels (only for type = "effect").

taxa

Optional data frame with columns Feature.ID and Taxon, used to label the taxa. If NULL (default), the taxonomy column of table is used.

x_axis_title, y_axis_title

Titles for the x- and y-axis. Default NULL: "Effect size" ("effect") or log2 fold change ("volcano") on x, and the (adjusted) p-value on y.

label_size

Numeric. Font size of the taxon labels drawn on significant points in the "volcano" plot. Default 3.5.

filter_uncultured

Logical. If TRUE, taxa whose name contains "uncultured"/"unculture" are still plotted as points but not labelled, keeping the volcano plot's text annotations to named taxa. Default FALSE.

save_table

Logical. If TRUE, saves the ALDEx2 results table as a tab-delimited file. Default FALSE. effect and diff.btw are saved as ALDEx2 returns them (second group in alphabetical order minus the first); in the plot, positive means higher in cond.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "aldex_pval_effect.txt".

Value

A ggplot object with the selected plot.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

# group_col must have exactly two groups; Location has two
# (Rhizosphere and Roots) in the bundled example data
aldex_volcano_plot(
    table = table,
    metadata = metadata,
    group_col = "Location",
    mc_samples = 16,
    type = "effect",
    col_inf = "#56B4E9",
    col_sup = "#E69F00",
    threshold_lower = -0.5,
    threshold_upper = 0.5,
    cond = "Rhizosphere",
    show_labels = TRUE
)

Alpha diversity along a continuous gradient

Description

Computes Hill numbers (q = 0, 1, 2) from table and plots them against a continuous metadata variable (e.g. distance to urban center, elevation, pH). It reports the Spearman rank correlation coefficient (rho, or Pearson r), its p-value, and optionally the linear regression R2R^2 and slope.

Usage

alpha_decay_plot(
  table,
  metadata,
  cont_var,
  group_col = NULL,
  method = "spearman",
  show_lm_stats = TRUE,
  facet_orientation = "horizontal",
  palette = "colorb",
  group_colors = NULL,
  x_axis_title = NULL,
  y_axis_title = "Effective number of features",
  title = NULL,
  show_legend = TRUE,
  legend_position = "bottom",
  free_y = TRUE,
  point_size = 2,
  line_width = 0.9,
  point_alpha = 0.8,
  annotation_size = 3.5,
  panel_label_case = "upper",
  panel_labels = NULL,
  panel_label_bold = TRUE,
  strip_text_bold = FALSE
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

cont_var

Character. Name of the continuous variable column in metadata to place on the x-axis (e.g. "dist_km").

group_col

Character. Name of the column in metadata that defines the groups, used to color the points and fit one regression line per group. Optional; NULL (default) for no groups.

method

Character. Correlation method for the statistic annotation. One of "spearman" (default) or "pearson".

show_lm_stats

Logical. If TRUE (default), adds R2R^2 and slope from the linear model to the annotation label.

facet_orientation

Character. "horizontal" (default) puts the three q0/q1/q2 panels in a row; "vertical" in a column.

palette

Character. Palette name: "colorb" (default, colorblind-friendly Okabe-Ito), "safe" (colorblind-friendly CARTO "Safe"), "earth" (CARTO "Earth", brown to teal; best for two or ordered groups), "grey", "viridis" or "brewer".

group_colors

Optional character vector of colors, one per group, named after the groups or in their order. Overrides palette.

x_axis_title

Character. Title of the x-axis. If NULL (default), the name of cont_var is used.

y_axis_title

Character. Title of the y-axis. Default "Effective number of features".

title

Character. Plot title. NULL (default) shows no title.

show_legend

Logical. If TRUE (default), the legend is shown.

legend_position

Character. Position of the legend: "bottom" (default), "top", "right" or "left".

free_y

Logical. If TRUE, the y-axis scale is free across facets. Default TRUE.

point_size

Numeric. Size of the points. Default 2.

line_width

Numeric. Width of regression lines. Default 0.9.

point_alpha

Numeric (0-1). Transparency of the points. Default 0.8.

annotation_size

Numeric. Font size for the stats annotation. Default 3.5.

panel_label_case

Character. Case of the panel tags: "upper" (default; A, B, C) or "lower" (a, b, c). Ignored if panel_labels is given.

panel_labels

Optional character vector of custom panel tags, one per panel (q0, q1, q2), used as-is (e.g. c("(a)", "(b)", "(c)")). Overrides panel_label_case.

panel_label_bold

Logical. If TRUE (default), panel tags are bold. Set to FALSE for journals that require plain (non-bold) panel tags.

strip_text_bold

Logical. If TRUE, the facet strip labels are bold. Default FALSE.

Value

A patchwork object with the three q0/q1/q2 panels, tagged as set by panel_label_case or panel_labels. It can still be modified: p & theme(...) changes every panel, p[[2]] + labs(...) a single one.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

loc_dist <- data.frame(Loc = 1:7, dist_km = seq(0, 12, length.out = 7))
metadata$dist_km <- loc_dist$dist_km[match(metadata$Loc, loc_dist$Loc)] +
    stats::rnorm(nrow(metadata), sd = 0.3)

# All samples, no grouping. Always tagged A/B/C (see panel_label_case and
# panel_labels to customize)
alpha_decay_plot(
    table        = table,
    metadata     = metadata,
    cont_var     = "dist_km",
    x_axis_title = "Distance (km)"
)

# Separate regression lines by location
alpha_decay_plot(
    table        = table,
    metadata     = metadata,
    cont_var     = "dist_km",
    x_axis_title = "Distance (km)",
    group_col    = "Location"
)

Alpha diversity indices plot

Description

Computes the Chao1, Shannon and Simpson indices of each sample (or Faith's phylogenetic diversity or Rao's quadratic entropy, see diversity) and plots them as box plots or bar plots, one panel per index, optionally faceted by one or two metadata variables and with statistical comparisons between groups.

Usage

alpha_diversity_plot(
  table,
  metadata,
  type = "boxplot",
  stat = NULL,
  p_adjust_method = "holm",
  x_col,
  fill_col,
  facet_by = NULL,
  facet_by2 = NULL,
  facet_orientation = "horizontal",
  palette = "colorb",
  group_colors = NULL,
  n_cols = NULL,
  n_rows = NULL,
  strip_color = "grey",
  show_legend = TRUE,
  title = NULL,
  legend_title = NULL,
  legend_position = "bottom",
  x_axis_title = NULL,
  y_axis_title = NULL,
  free_y = FALSE,
  rarefy_depth = NULL,
  panel_label_case = "upper",
  panel_labels = NULL,
  panel_label_bold = TRUE,
  x_label_angle = 0,
  strip_text_bold = FALSE,
  aspect_ratio = NULL,
  save_table = FALSE,
  table_filename = "diversity.txt",
  diversity = "taxonomic",
  tree = NULL,
  traits = NULL
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

type

Type of plot: "boxplot" (default) or "barplot". Case-insensitive.

stat

Character or NULL. Statistical test to compare the groups within each panel. "wilcox.test" or "t.test" compare every pair of groups, each with its own bracket and p-value (ggpubr::stat_pwc()); "kruskal.test" or "anova" give one global p-value per panel. Default NULL (no test shown).

p_adjust_method

Character. Multiple-testing correction for the pairwise tests (stat = "wilcox.test" or "t.test"), applied within each panel, any method of stats::p.adjust(). Default "holm"; "none" uses the raw p-values.

x_col

Character. Name of the column in metadata for the x-axis.

fill_col

Character. Name of the column in metadata for the fill color.

facet_by

Character. Name of the column in metadata to facet the plot by. Optional; NULL (default) for no facets.

facet_by2

Character. Name of a second column in metadata to facet by. Optional; NULL (default) for none.

facet_orientation

Character. "horizontal" (default) puts the facet_by facets in columns; "vertical" in rows. Case-insensitive.

palette

Character. Palette name: "colorb" (default, colorblind-friendly Okabe-Ito), "safe" (colorblind-friendly CARTO "Safe"), "earth" (CARTO "Earth", brown to teal; best for two or ordered groups), "grey", "viridis" or "brewer". Case-insensitive.

group_colors

Optional character vector of colors, one per group, named after the groups or in their order. Overrides palette.

n_cols

Integer. Number of columns of the facet grid. If NULL (default), set automatically.

n_rows

Integer. Number of rows of the facet grid. If NULL (default), set automatically.

strip_color

Character. Background color of the facet strips (used when facet_by is set). Default "grey".

show_legend

Logical. If TRUE (default), the legend is shown.

title

Character. Plot title. NULL (default) shows no title.

legend_title

Character. Title of the legend. If NULL (default), the legend has no title.

legend_position

Character. Position of the legend: "bottom" (default), "top", "right" or "left".

x_axis_title

Character. Title of the x-axis. Default NULL (no title).

y_axis_title

Character. Title of the y-axis. Default NULL: "Diversity measure", "Branch length" (Faith PD) or "Mean functional distance" (Rao Q).

free_y

Logical. Each index always has its own y-axis scale (Chao1, Shannon and Simpson have very different ranges). If FALSE (default), that scale is shared by all the panels of the same index, so the groups can be compared across facets. If TRUE, every panel gets its own scale.

rarefy_depth

Integer. If given, the samples are rarefied to this depth (vegan::rrarefy()) before computing the indices. Default NULL (no rarefaction).

panel_label_case

Character. Case of the panel tags (added to every panel): "upper" (default; A, B, C) or "lower" (a, b, c). Ignored if panel_labels is given.

panel_labels

Optional character vector of custom panel tags, one per panel, used as-is (e.g. c("(a)", "(b)", "(c)")). Overrides panel_label_case.

panel_label_bold

Logical. If TRUE (default), panel tags are bold. Set to FALSE for journals that require plain (non-bold) panel tags.

x_label_angle

Numeric. Rotation (degrees) of the x-axis labels. Default 0 (horizontal); use 45 or 90 if they overlap.

strip_text_bold

Logical. If TRUE, the facet strip labels are bold. Default FALSE.

aspect_ratio

Numeric. Aspect ratio (height/width) of each panel. Default NULL (automatic).

save_table

Logical. If TRUE, saves the diversity table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "diversity.txt".

diversity

Character. "taxonomic" (default; Chao1, Shannon and Simpson), "phylogenetic" (Faith's PD, the summed branch length up to the root; needs tree) or "functional" (Rao's Q, the mean Gower distance between two random reads; needs traits). Case-insensitive.

tree

A rooted phylo tree whose tip labels are the taxa of table. Used when diversity = "phylogenetic".

traits

A data frame with taxa in rows and traits in columns. Used when diversity = "functional".

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

# Panel tags (A/B/C) are always added (see panel_label_case and
# panel_labels to customize their case/format); stat additionally
# overlays p-value annotations on each panel
alpha_diversity_plot(
  table            = table,
  metadata         = metadata,
  type             = "barplot",
  x_col            = "Location",
  fill_col         = "Location",
  facet_by         = "Treatment",
  free_y           = TRUE,
  legend_position  = "top",
  stat             = "t.test",
  panel_label_case = "upper"
)

Alpha diversity vs sequencing depth

Description

Computes the Hill numbers (q = 0, 1, 2) of each sample and plots each against the sequencing depth (total reads), with a regression line and the correlation coefficient, combining the three panels in one figure.

Usage

alpha_hill_corr_plot(
  table,
  method = "spearman",
  facet_orientation = "horizontal",
  title = "auto",
  panel_label_case = "upper",
  panel_labels = NULL,
  panel_label_bold = TRUE,
  save_table = FALSE,
  table_filename = "hill.txt",
  x_axis_title = "Sequencing depth (number of reads)"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

method

Character. Correlation method passed to ggpubr::stat_cor. One of "spearman" (default, rank-based and robust to non-linear/non-normal relationships), "pearson", or "kendall".

facet_orientation

Character. "horizontal" (default) puts the three q0/q1/q2 panels in a row; "vertical" in a column.

title

Character. Plot title. "auto" (default) shows "Alpha diversity vs sequencing depth"; NULL shows no title; any other text is used as the title.

panel_label_case

Character. Case of the panel tags: "upper" (default; A, B, C) or "lower" (a, b, c). Ignored if panel_labels is given.

panel_labels

Optional character vector of custom panel tags, one per panel (q0, q1, q2), used as-is (e.g. c("(a)", "(b)", "(c)")). Overrides panel_label_case.

panel_label_bold

Logical. If TRUE (default), panel tags are bold. Set to FALSE for journals that require plain (non-bold) panel tags.

save_table

Logical. If TRUE, saves the Hill numbers table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "hill.txt".

x_axis_title

Character. Title of the x-axis of the three panels. Default "Sequencing depth (number of reads)".

Value

A patchwork object with the three q0/q1/q2 panels.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

# Always tagged A/B/C (see panel_label_case and panel_labels to customize)
alpha_hill_corr_plot(
    table             = table,
    facet_orientation = "horizontal"
)

## Using Pearson correlation instead of the default Spearman
alpha_hill_corr_plot(
    table  = table,
    method = "pearson"
)

Hill numbers alpha diversity plot

Description

Computes the Hill numbers (q = 0, 1, 2) of each sample and plots them as box plots or bar plots, one panel per order q, optionally faceted by one or two metadata variables and with statistical comparisons between groups.

Usage

alpha_hill_plot(
  table,
  metadata,
  type = "boxplot",
  stat = NULL,
  p_adjust_method = "holm",
  x_col,
  fill_col,
  facet_by = NULL,
  facet_by2 = NULL,
  facet_orientation = "horizontal",
  palette = "colorb",
  group_colors = NULL,
  n_cols = NULL,
  n_rows = NULL,
  strip_color = "grey",
  show_legend = TRUE,
  title = NULL,
  legend_title = NULL,
  legend_position = "bottom",
  x_axis_title = NULL,
  y_axis_title = NULL,
  free_y = FALSE,
  panel_label_case = "upper",
  panel_labels = NULL,
  panel_label_bold = TRUE,
  x_label_angle = 0,
  strip_text_bold = FALSE,
  aspect_ratio = NULL,
  save_table = FALSE,
  table_filename = "hill.txt",
  diversity = "taxonomic",
  tree = NULL,
  traits = NULL,
  tau = NULL
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

type

Type of plot: "boxplot" (default) or "barplot". Case-insensitive.

stat

Character or NULL. Statistical test to compare the groups within each panel. "wilcox.test" or "t.test" compare every pair of groups, each with its own bracket and p-value (ggpubr::stat_pwc()); "kruskal.test" or "anova" give one global p-value per panel. Default NULL (no test shown).

p_adjust_method

Character. Multiple-testing correction for the pairwise tests (stat = "wilcox.test" or "t.test"), applied within each panel, any method of stats::p.adjust(). Default "holm"; "none" uses the raw p-values.

x_col

Character. Name of the column in metadata for the x-axis.

fill_col

Character. Name of the column in metadata for the fill color.

facet_by

Character. Name of the column in metadata to facet the plot by. Optional; NULL (default) for no facets.

facet_by2

Character. Name of a second column in metadata to facet by. Optional; NULL (default) for none.

facet_orientation

Character. "horizontal" (default) puts the facet_by facets in columns; "vertical" in rows. Case-insensitive.

palette

Character. Palette name: "colorb" (default, colorblind-friendly Okabe-Ito), "safe" (colorblind-friendly CARTO "Safe"), "earth" (CARTO "Earth", brown to teal; best for two or ordered groups), "grey", "viridis" or "brewer". Case-insensitive.

group_colors

Optional character vector of colors, one per group, named after the groups or in their order. Overrides palette.

n_cols

Integer. Number of columns of the facet grid. If NULL (default), set automatically.

n_rows

Integer. Number of rows of the facet grid. If NULL (default), set automatically.

strip_color

Character. Background color of the facet strips (used when facet_by is set). Default "grey".

show_legend

Logical. If TRUE (default), the legend is shown.

title

Character. Plot title. NULL (default) shows no title.

legend_title

Character. Title of the legend. If NULL (default), the legend has no title.

legend_position

Character. Position of the legend: "bottom" (default), "top", "right" or "left".

x_axis_title

Character. Title of the x-axis. Default NULL (no title).

y_axis_title

Character. Title of the y-axis. Default NULL: the unit of diversity: "Effective number of features", "Effective number of lineages" or "Effective number of functional groups".

free_y

Logical. Each order q always has its own y-axis scale (q0 is usually much larger than q2). If FALSE (default), that scale is shared by all the panels of the same order, so the groups can be compared across facets. If TRUE, every panel gets its own scale.

panel_label_case

Character. Case of the panel tags (added to every panel): "upper" (default; A, B, C) or "lower" (a, b, c). Ignored if panel_labels is given.

panel_labels

Optional character vector of custom panel tags, one per panel, used as-is (e.g. c("(a)", "(b)", "(c)")). Overrides panel_label_case.

panel_label_bold

Logical. If TRUE (default), panel tags are bold. Set to FALSE for journals that require plain (non-bold) panel tags.

x_label_angle

Numeric. Rotation (degrees) of the x-axis labels. Default 0 (horizontal); use 45 or 90 if they overlap.

strip_text_bold

Logical. If TRUE, the facet strip labels are bold. Default FALSE.

aspect_ratio

Numeric. Aspect ratio (height/width) of each panel. Default NULL (automatic).

save_table

Logical. If TRUE, saves the Hill numbers table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "hill.txt".

diversity

Character. "taxonomic" (default, Hill numbers of the abundances), "phylogenetic" (needs tree) or "functional" (needs traits), computed with hilldiv3::hilldiv(). Phylogenetic values are effective numbers of lineages read at one common tree depth (reference = "pool"), so a sample can fall slightly below

  1. Functional values are effective numbers of functional groups at the threshold tau. Case-insensitive.

tree

A rooted phylo tree (e.g. from ape::read.tree()) whose tip labels are the taxa of table. Used when diversity = "phylogenetic".

traits

A data frame with taxa in rows and traits in columns (e.g. the EC or KO copy numbers predicted per ASV by PICRUSt2), converted to Gower distances with hilldiv3::traits2dist(). Used when diversity = "functional".

tau

Numeric. Threshold of functional distinctiveness: taxa at this distance or more count as different functional groups. NULL (default) uses the mean distance between two reads of the pooled samples (Chao et al. 2019). Used when diversity = "functional".

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

# Panel tags (A/B/C) are always added (see panel_label_case and
# panel_labels to customize their case/format); stat additionally
# overlays p-value annotations on each panel
alpha_hill_plot(
  table            = table,
  metadata         = metadata,
  type             = "boxplot",
  x_col            = "Location",
  fill_col         = "Location",
  facet_by         = "Treatment",
  legend_position  = "top",
  stat             = "kruskal.test",
  panel_label_case = "upper"
)

ANCOMBC2 differential abundance bar/heatmap plot

Description

Runs ANCOMBC2 on a table and metadata, then visualizes differentially abundant taxa.

Usage

ancombc_plot(
  table,
  metadata,
  group_col,
  level = "genus",
  min_prevalence = 0.1,
  p_adjust_method = "holm",
  formula = NULL,
  rand_formula = NULL,
  ref_level = NULL,
  diverging_palette = "BuOr",
  x_axis_title = NULL,
  y_axis_title = NULL,
  bar_colors = c("#56B4E9", "#E69F00"),
  save_table = FALSE,
  table_filename = "ancombc_results.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

group_col

Character. Name of the column in metadata that defines the groups. If it is numeric, it is treated as a continuous covariate.

level

Character or NULL. Taxonomic level to agglomerate to before running ancombc2 (e.g. "genus", "family"; case-insensitive). Default "genus". Pass NULL to skip agglomeration and run ANCOMBC2 directly on the ASV/OTU/species-level table (rows of table, as-is).

min_prevalence

Numeric. Prevalence cut-off passed to ancombc2 (default 0.1). Lower values retain more taxa.

p_adjust_method

Character. Multiple-testing correction for the ANCOMBC2 p-values of the taxa (passed to ancombc2()), any method of stats::p.adjust(). Default "holm"; "none" uses the raw p-values. Use "BH" for a less strict correction with few samples.

formula

Character. Right-hand side of the fixed-effects formula passed to ancombc2 (e.g. "group + age"). If NULL (default) group_col is used alone.

rand_formula

Character. Random-effects formula passed to ancombc2 for mixed models (e.g. "~ 1 | subject_id"). Default NULL.

ref_level

Character. Reference level of group_col, the baseline of the comparisons. If NULL (default), the first factor level is used (e.g. ref_level = "P2" compares every other group against P2).

diverging_palette

Character. Colorblind-friendly diverging palette of the heatmap (3 or more groups): "BuOr" (blue-orange, default), "BuVm" (blue-vermillion), "BuPk" (blue-pink), "GnPk" (green-pink) or "PuYl" (purple-yellow). Not used by the bar plot, which uses bar_colors.

x_axis_title, y_axis_title

Titles for the x- and y-axis. Default NULL: the log fold change of the comparison on x of the bar plots, and no title otherwise.

bar_colors

Character vector of two colors for the bar plot: the first for the taxa higher in the non-reference group, the second for those higher in the reference group. Default c("#56B4E9", "#E69F00").

save_table

Logical. If TRUE, saves the ANCOMBC2 results table (log fold change, standard error, p- and q-values and diff_ of each term) as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "ancombc_results.txt".

Value

A ggplot object: a bar plot (2 groups) or a heatmap (3 or more groups).

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)


ancombc_plot(
    table = table,
    metadata = metadata,
    group_col = "Location",
    min_prevalence = 0.3,
    p_adjust_method = "BH"
)

Distance-decay of community similarity plot

Description

Computes the pairwise community dissimilarity (Jaccard, Morisita-Horn, Bray-Curtis or another vegdist method) and the pairwise geographic distance from the sample coordinates in metadata, and tests their relationship with a Mantel test.

Usage

beta_decay_plot(
  table,
  metadata,
  lat_col,
  lon_col,
  group_col = NULL,
  palette = "colorb",
  distance = "jaccard",
  method = "spearman",
  permutations = 999,
  show_lm_stats = TRUE,
  point_color = "black",
  line_color = "#D55E00",
  point_size = 1,
  point_alpha = 0.5,
  annotation_size = 3.5,
  x_axis_title = "Spatial distance (km)",
  y_axis_title = NULL,
  title = NULL
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table). It must also have the latitude and longitude columns.

lat_col

Character. Name of the latitude column in metadata (decimal degrees).

lon_col

Character. Name of the longitude column in metadata (decimal degrees).

group_col

Character. Name of the column in metadata that defines the groups. If given, only pairs of samples from the same group are kept, with one color per group. Optional; NULL (default) for no groups.

palette

Palette name ("colorb" (default), "safe", "earth", "grey", "viridis" or "brewer") or a vector of colors, one per group. Only used when group_col is given.

distance

Character. Dissimilarity metric passed to vegan::vegdist. Common options: "jaccard" (default), "horn" (Morisita-Horn / Hill q = 1 analogue), "bray" (Bray-Curtis). Any method accepted by vegdist is valid. Case-insensitive.

method

Character. Correlation method for the Mantel test: "spearman" (default) or "pearson". Case-insensitive.

permutations

Integer. Number of permutations for the Mantel test. Default 999.

show_lm_stats

Logical. If TRUE (default), adds R2R^2 to the annotation label in addition to the Mantel r, p-value, and slope.

point_color

Character. Color of scatter points. Default "black".

line_color

Character. Color of the regression line. Default "#D55E00".

point_size

Numeric. Size of the points. Default 1.

point_alpha

Numeric (0-1). Transparency of the points. Default 0.5.

annotation_size

Numeric. Font size for the stats annotation. Default 3.5.

x_axis_title

Character. Title of the x-axis. Default "Spatial distance (km)".

y_axis_title

Character. Title of the y-axis. If NULL (default), it is built automatically.

title

Character. Plot title. NULL (default) shows no title.

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

loc_coords <- data.frame(
    Loc = 1:7,
    lat = 19.0 + seq(0, 0.6, length.out = 7),
    lon = -99.0 + seq(0, 0.6, length.out = 7)
)
metadata$lat <- loc_coords$lat[match(metadata$Loc, loc_coords$Loc)]
metadata$lon <- loc_coords$lon[match(metadata$Loc, loc_coords$Loc)]

# Jaccard + Spearman Mantel (default)
beta_decay_plot(
    table    = table,
    metadata = metadata,
    lat_col  = "lat",
    lon_col  = "lon"
)

# Horn dissimilarity + Spearman Mantel
beta_decay_plot(
    table    = table,
    metadata = metadata,
    lat_col  = "lat",
    lon_col  = "lon",
    distance = "horn",
    method   = "spearman"
)

# Separate Mantel test per location
beta_decay_plot(
    table     = table,
    metadata  = metadata,
    lat_col   = "lat",
    lon_col   = "lon",
    group_col = "Location"
)

Beta diversity boxplot

Description

Computes the pairwise beta diversity between samples (shared features, turnover or nestedness) and plots it as box plots, one box per pair of groups.

Usage

beta_dissimilarity_plot(
  table,
  metadata,
  comparison_condition1 = NULL,
  condition1_col,
  condition2_col = NULL,
  facet_colors = NULL,
  group_colors = NULL,
  x_axis_title = "Condition",
  y_axis_title = NULL,
  partition = c("shared", "turnover", "nestedness"),
  family = c("sorensen", "jaccard"),
  stat = NULL,
  p_adjust_method = "holm",
  show_x_labels = TRUE,
  x_label_angle = 0,
  strip_text_bold = FALSE,
  strip_text_color = "black",
  aspect_ratio = NULL,
  save_table = FALSE,
  table_filename = "betadiv_table.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

comparison_condition1

Optional character vector with the pairs of groups of condition1_col to show (e.g. "Rhizosphere_vs_Roots"; the order of the two groups does not matter). If NULL (default), all pairs are shown.

condition1_col

Character. Name of the column in metadata whose groups are compared: each box is one pair of groups.

condition2_col

Character. Name of a second column in metadata. If given, only pairs of samples with the same value are kept, and the plot is faceted by it. Optional; NULL (default) for none.

facet_colors

Optional character vector of background colors for the facet strips. If NULL (default), a neutral "grey85" is used.

group_colors

Optional character vector of colors, one per comparison on the x-axis, named after them or in their order. If NULL (default), the colorblind-friendly Okabe-Ito palette is used.

x_axis_title

Character. Title of the x-axis. Default "Condition".

y_axis_title

Character. Title of the y-axis. If NULL (default), it is built automatically.

partition

Type of beta diversity to compute: "shared" (default), "turnover", or "nestedness". Case-insensitive.

family

Dissimilarity family for the turnover/nestedness partition: "sorensen" (default) or "jaccard". Case-insensitive.

stat

Character or NULL. Statistical test to compare the boxes within each panel. "wilcox.test" or "t.test" compare every pair of boxes, each with its own bracket and p-value (ggpubr::stat_pwc()); "kruskal.test" or "anova" give one global p-value per panel (ggpubr::stat_compare_means()). Default NULL (no test shown).

p_adjust_method

Character. Multiple-testing correction for the pairwise tests (stat = "wilcox.test" or "t.test"), applied within each panel, any method of stats::p.adjust(). Default "holm"; "none" uses the raw p-values.

show_x_labels

Logical. If TRUE (default), the x-axis labels are shown.

x_label_angle

Numeric. Rotation (degrees) of the x-axis labels (when show_x_labels = TRUE). Default 0 (horizontal); use 45 or 90 if they overlap.

strip_text_bold

Logical. If TRUE, the facet strip labels are bold. Default FALSE.

strip_text_color

Color of the facet strip labels, which sit on the facet_colors backgrounds. Default "black" (the default facet_colors is a light "grey85"; pass "white" if you supply darker facet_colors).

aspect_ratio

Numeric. Aspect ratio (height/width) of each panel. Default NULL (automatic).

save_table

Logical. If TRUE, saves the beta diversity table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "betadiv_table.txt".

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

beta_dissimilarity_plot(
    table = table,
    metadata = metadata,
    comparison_condition1 = c("Rhizosphere_vs_Roots"),
    condition1_col = "Location",
    condition2_col = "Treatment",
    x_axis_title = "Samples",
    partition = "shared",
    family = "sorensen"
)

Beta diversity ordination plot

Description

Computes the beta diversity between samples with several distance metrics (including the compositional CLR/Aitchison distance via ALDEx2) and plots a PCA, PCoA or NMDS ordination.

Usage

beta_ord_plot(
  table,
  metadata,
  distance = "compositional",
  mc_samples = 1,
  ordination = "PCA",
  group_col = NULL,
  palette = "colorb",
  shape_col = NULL,
  legend_title = NULL,
  taxonomy_db = "silva",
  arrows_size = 10,
  top_n = 5,
  title = "auto",
  save_table = FALSE,
  table_filename = "ordination_scores.txt",
  q = 1,
  diversity = "taxonomic",
  tree = NULL,
  traits = NULL,
  tau = NULL
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

distance

Distance method: one of "euclidean", "bray", "jaccard", "sorensen", "compositional" (default; CLR/Aitchison via ALDEx2), "aitchison", "robust.aitchison", or the Hill-number dissimilarities "U", "C", "V" or "S" of hilldiv3::hillpair() (with PCoA or NMDS; see q). Case-insensitive. Note: ordination = "PCA" requires distance = "compositional".

mc_samples

Number of ALDEx2 Monte Carlo instances used when distance = "compositional". With 1 (default) the clr values of one random instance are used: fast, but the result changes between runs (use set.seed()). With more, the clr values are averaged across instances, which gives an almost identical result in every run; 128 (ALDEx2's default) is suggested for final analyses, and takes longer. Ignored for other distances.

ordination

Ordination method: one of "PCA" (default), "PCoA", or "NMDS". Case-insensitive.

group_col

Character. Name of the column in metadata used to color the points; if it is numeric, a continuous color scale is used. Optional; NULL (default) for no groups.

palette

Either a palette name or a vector of fixed colors; which scale it produces depends on whether group_col is discrete or continuous.

  • Named, discrete group_col: one of "colorb" (default; qualitative colorblind-friendly palette), "safe" (colorblind-friendly CARTO "Safe"), "earth" (CARTO "Earth", brown to teal; best for two or ordered groups), "grey", "viridis", or "brewer" ("Set2").

  • Named, continuous group_col: "viridis" (default; option = "cividis") or "gradient"

  • Vector of colors, discrete group_col: used as-is, one color per level (scale_*_manual).

  • Vector of colors, continuous group_col: used as gradient stops (scale_*_gradientn).

shape_col

Character. Name of the column in metadata used for the point shapes. Optional; NULL (default) for one shape.

legend_title

Character. Title of the legend. If NULL (default), the name of group_col is used.

taxonomy_db

Character. Database the taxonomy strings come from: "silva" (default), "gg2" (Greengenes2, also "gg"), "unite" or "Kraken2" (also "kraken"). Case-insensitive. Only used when ordination = "PCA".

arrows_size

Numeric. Size/length scaling factor for biplot arrows. Default 10.

top_n

Integer. Number of taxa that contribute most to the PCA, drawn as arrows. Default 5.

title

Character. Plot title. "auto" (default) shows "Ordination - <distance>"; NULL shows no title; any other text is used as the title.

save_table

Logical. If TRUE, saves the ordination scores and loadings (one table) as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "ordination_scores.txt".

q

Numeric. Order of the Hill-number dissimilarities "U", "C", "V" and "S": 0 (presence/absence), 1 (default) or 2 (dominant taxa). Ignored by the other distances.

diversity

Character. What the Hill-number dissimilarities use: "taxonomic" (default), "phylogenetic" (needs tree) or "functional" (needs traits). Case-insensitive.

tree

A rooted phylo tree whose tip labels are the taxa of table. Used when diversity = "phylogenetic".

traits

A data frame with taxa in rows and traits in columns. Used when diversity = "functional".

tau

Numeric. Threshold of functional distinctiveness: taxa at this distance or more count as different functional groups. NULL (default) uses the mean distance between two reads of the pooled samples (Chao et al. 2019). Used when diversity = "functional".

Details

With distance = "compositional" and mc_samples = 1, the clr values come from one random Monte Carlo instance of ALDEx2::aldex.clr(); call set.seed() before the function to make the result reproducible, or use mc_samples = 128.

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

beta_ord_plot(
    table      = table,
    metadata   = metadata,
    distance   = "aitchison",
    ordination = "NMDS",
    group_col  = "Location",
    top_n      = 5
)

Beta diversity partition ordination

Description

Partitions the beta diversity (Jaccard or Sorensen) into its turnover and nestedness components with betapart, and plots a PCoA of each component (vegan::betadisper()) with the samples linked to their group centroid.

Usage

beta_partition_ord_plot(
  table,
  metadata,
  family = "jaccard",
  group_col,
  shape_col = NULL,
  legend_title = NULL,
  point_size = 3,
  group_colors = NULL,
  panel_label_case = "upper",
  panel_labels = NULL,
  panel_label_bold = TRUE,
  save_table = FALSE,
  table_filename = "beta_partition"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

family

Dissimilarity family for the partition: "jaccard" (default) or "sorensen". Case-insensitive.

group_col

Character. Name of the column in metadata that defines the groups. Required: the dispersion and the lines to the centroid are computed per group.

shape_col

Character. Name of the column in metadata used for the point shapes. Optional; NULL (default) for one shape.

legend_title

Character. Title of the legend. If NULL (default), the name of group_col is used.

point_size

Numeric. Size of the points. Default 3.

group_colors

Optional character vector of colors, one per group, named after the groups or in their order. If NULL (default), the colorblind-friendly Okabe-Ito palette is used.

panel_label_case

Character. Case of the panel tags: "upper" (default; A, B, C) or "lower" (a, b, c). Ignored if panel_labels is given.

panel_labels

Optional character vector of custom panel tags, one per panel (Jaccard/Sorensen, turnover, nestedness), used as-is (e.g. c("(a)", "(b)", "(c)")). Overrides panel_label_case.

panel_label_bold

Logical. If TRUE (default), panel tags are bold. Set to FALSE for journals that require plain (non-bold) panel tags.

save_table

Logical. If TRUE, saves the PCoA coordinates of the three ordinations as tab-delimited files. Default FALSE.

table_filename

Character. Base name or path of the saved files (used when save_table = TRUE): three files, <name>_jacs.txt, <name>_jtus.txt and <name>_jnes.txt. Default "beta_partition".

Value

A patchwork object with the three ordinations (Jaccard/Sorensen, turnover and nestedness).

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

beta_partition_ord_plot(
    table      = table,
    metadata   = metadata,
    group_col  = "Location",
    point_size = 4
)

PERMANOVA or betadisper results table

Description

Runs a PERMANOVA (vegan::adonis2()) or a test of homogeneity of dispersions (vegan::betadisper()) on the distances between samples and returns the results as a table figure.

Usage

beta_test_table(
  table,
  metadata,
  formula_str,
  distance = "euclidean",
  test = c("permanova", "betadisper"),
  permutations = 999,
  mc_samples = 1,
  strata_var = NULL,
  digits = 3,
  save_table = FALSE,
  table_filename = "beta_test_results.txt",
  q = 1,
  diversity = "taxonomic",
  tree = NULL,
  traits = NULL,
  tau = NULL
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

formula_str

Character. Right-hand side of the model formula, with columns of metadata (e.g. "Type_of_soil*Treatment").

distance

Character. Distance metric: "compositional" (CLR with ALDEx2), "aitchison", "robust.aitchison" or any other method of vegan::vegdist() (e.g. "bray", "jaccard"), or the Hill-number dissimilarities "U", "C", "V" or "S" of hilldiv3::hillpair() (see q). Default "euclidean". Case-insensitive. Ignored when table is already a distance.

test

Statistical test to run: one of "permanova" (default) or "betadisper". Case-insensitive.

permutations

Integer. Number of permutations for the test. Default 999.

mc_samples

Number of ALDEx2 Monte Carlo instances used when distance = "compositional". With 1 (default) the clr values of one random instance are used: fast, but the result changes between runs (use set.seed()). With more, the clr values are averaged across instances, which gives an almost identical result in every run; 128 (ALDEx2's default) is suggested for final analyses, and takes longer. Ignored for other distances.

strata_var

Character. Name of a column in metadata within which the permutations are restricted (strata). Optional; NULL (default) for none.

digits

Integer. Decimal places of the numeric columns (except the p-value). Default 3.

save_table

Logical. If TRUE, saves the results table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "beta_test_results.txt".

q

Numeric. Order of the Hill-number dissimilarities "U", "C", "V" and "S": 0 (presence/absence), 1 (default) or 2 (dominant taxa). Ignored by the other distances.

diversity

Character. What the Hill-number dissimilarities use: "taxonomic" (default), "phylogenetic" (needs tree) or "functional" (needs traits). Case-insensitive.

tree

A rooted phylo tree whose tip labels are the taxa of table. Used when diversity = "phylogenetic".

traits

A data frame with taxa in rows and traits in columns. Used when diversity = "functional".

tau

Numeric. Threshold of functional distinctiveness: taxa at this distance or more count as different functional groups. NULL (default) uses the mean distance between two reads of the pooled samples (Chao et al. 2019). Used when diversity = "functional".

Details

The first column of metadata must hold the sample IDs; metadata rows are matched to the samples by ID, so their order doesn't matter. A precomputed distance is used as-is (distance is ignored). The p-values come from permutations; call set.seed() before the function to make the result reproducible.

Value

A ggplot object (ggpubr::ggtexttable()) with the results table; significant p-values are in bold. Use save_table = TRUE to get the results as a tab-delimited file.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

# Example using a data frame
beta_test_table(
    table = table,
    metadata = metadata,
    formula_str = "Location*Treatment",
    distance = "bray",
    test = "permanova",
    permutations = 999,
    strata_var = "Plot"
)

# Example using a distance matrix
dist_matrix <- vegan::vegdist(
    t(table[, setdiff(colnames(table), "taxonomy")]),
    method = "bray"
)
beta_test_table(
    table       = dist_matrix,
    metadata    = metadata,
    formula_str = "Location",
    test        = "betadisper"
)

# Compositional PERMANOVA (CLR via ALDEx2, then Euclidean)
beta_test_table(
    table = table,
    metadata = metadata,
    formula_str = "Location",
    distance = "compositional",
    test = "permanova",
    permutations = 999
)

Box plot of pairwise feature turnover (Hill numbers)

Description

Computes the pairwise beta diversity between samples with Hill numbers (q = 0, 1, 2; same values as hillR::hill_taxa_parti_pairwise()) and plots the proportion of feature turnover (β−1\beta - 1, from 0 = identical to 1 = no shared features) as box plots, one facet row per Hill order. q = 0 weighs all features equally (presence/absence), q = 1 weighs them by their abundance and q = 2 gives more weight to dominant features.

Usage

beta_turnover_plot(
  table,
  metadata,
  comparison_condition1,
  comparison_condition2 = NULL,
  condition1_col,
  condition2_col = NULL,
  facet_colors = NULL,
  group_colors = NULL,
  x_axis_title = "Section",
  y_axis_title = "Proportion of feature turnover",
  show_x_labels = FALSE,
  x_label_angle = 0,
  strip_text_bold = FALSE,
  strip_text_color = "white",
  aspect_ratio = NULL,
  stat = NULL,
  p_adjust_method = "holm",
  save_table = FALSE,
  table_filename = "betadiv_turnover.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

comparison_condition1

Character vector with the pairs of groups of condition1_col to show (e.g. "Rhizosphere_vs_Roots", "Rhizosphere_vs_Rhizosphere"; the order of the two groups does not matter). Each pair is one box, labeled as written.

comparison_condition2

Optional character vector with the pairs of groups of condition2_col to keep (e.g. "TC_vs_TC"); the plot is faceted by them. Requires condition2_col. If NULL (default), no pairs are filtered by condition2_col.

condition1_col

Character. Name of the column in metadata whose groups are compared (the pairs of comparison_condition1).

condition2_col

Optional. Metadata column used to build comparison_condition2's group pairs, and to facet the plot. Required when comparison_condition2 is set. If given without comparison_condition2, the plot is faceted by it keeping only pairs of samples with the same value (e.g. "TC_vs_TC", "TD_vs_TD").

facet_colors

Optional character vector of background colors for the facet strips. If NULL (default), a neutral "grey85" is used.

group_colors

Optional character vector of colors, one per comparison on the x-axis, named after them or in their order. If NULL (default), the colorblind-friendly Okabe-Ito palette is used.

x_axis_title

Character. Title of the x-axis. Default "Section".

y_axis_title

Character. Title of the y-axis. Default "Proportion of feature turnover".

show_x_labels

Logical. If TRUE, the x-axis labels are shown. Default FALSE, since the groups are already named in the legend.

x_label_angle

Numeric. Rotation (degrees) of the x-axis labels (when show_x_labels = TRUE). Default 0 (horizontal); use 45 or 90 if they overlap.

strip_text_bold

Logical. If TRUE, the facet strip labels are bold. Default FALSE.

strip_text_color

Color of the top (x) facet strip labels, which sit on the facet_colors backgrounds. Default "white", unless facet_colors is left at its own light "grey85" default, in which case this defaults to "black" instead so it stays legible.

aspect_ratio

Numeric. Aspect ratio (height/width) of each panel. Default NULL (automatic).

stat

Character or NULL. Statistical test to compare the boxes within each panel. "wilcox.test" or "t.test" compare every pair of boxes, each with its own bracket and p-value (ggpubr::stat_pwc()); "kruskal.test" or "anova" give one global p-value per panel (ggpubr::stat_compare_means()). Default NULL (no test shown).

p_adjust_method

Character. Multiple-testing correction for the pairwise tests (stat = "wilcox.test" or "t.test"), applied within each panel, any method of stats::p.adjust(). Default "holm"; "none" uses the raw p-values.

save_table

Logical. If TRUE, saves the turnover table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "betadiv_turnover.txt".

Details

Each box is one group pair from condition1_col, so a between-group comparison (e.g. "Rhizosphere_vs_Roots") can be contrasted with a within-group baseline (e.g. "Rhizosphere_vs_Rhizosphere"): if the between-group turnover is higher, the groups host distinct communities beyond the variability among replicates of the same group. An optional condition2_col keeps only pairs from the same level (e.g. the same treatment) and facets by it, so the comparison is not confounded by it.

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)
colnames(metadata)[1] <- "OTUID"

# comparison_condition1/2 match group pairs regardless of order, so listing
# "Rhizosphere_vs_Roots" also catches pairs the self-join recorded the
# other way around ("Roots_vs_Rhizosphere") - no need to list both.
beta_turnover_plot(
    table = table,
    metadata = metadata,
    comparison_condition1 = c("Rhizosphere_vs_Roots", "Rhizosphere_vs_Rhizosphere"),
    comparison_condition2 = c("Control_vs_Control", "Moderate_drought_vs_Moderate_drought"),
    condition1_col = "Location",
    condition2_col = "Treatment",
    facet_colors = c("#5D478B", "#8B668B"),
    group_colors = c(
        "Rhizosphere_vs_Roots" = "#56B4E9",
        "Rhizosphere_vs_Rhizosphere" = "#E69F00"
    )
)

CCA/RDA biplot

Description

Performs a Canonical Correspondence Analysis (CCA) or a Redundancy Analysis (RDA) of the abundance table constrained by environmental variables, and plots the samples and the environmental vectors as a biplot.

Usage

cca_rda_biplot(
  table,
  env_data = NULL,
  env_vars,
  method = "hell",
  metadata,
  group_col = NULL,
  group_colors = NULL,
  legend_title = NULL,
  scale_env = TRUE,
  pval_threshold = 0.05,
  p_adjust_method = "none",
  show_all_env_vectors = FALSE,
  analysis = "CCA",
  scale_arrows = 1,
  title = "auto",
  save_table = FALSE,
  table_filename = "cca_rda_scores.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

env_data

Optional data frame of environmental variables, with row names matching the sample names in table. Default NULL: the variables named in env_vars are taken from metadata. Use it only when the variables are in a separate table.

env_vars

A character vector with the names of environmental variables (columns of metadata, or of env_data if given) to include in the analysis.

method

Character. Transformation of the abundances, passed to vegan::decostand(). Default "hell" (Hellinger).

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table). The environmental variables can be columns of metadata (see env_vars).

group_col

Character. Name of the column in metadata that defines the groups. Used to color the samples. Optional; NULL (default) for no groups.

group_colors

Optional character vector of colors, one per group, named after the groups or in their order. If NULL (default), the colorblind-friendly Okabe-Ito palette is used.

legend_title

Character. Title of the legend. If NULL (default), the name of group_col is used.

scale_env

Logical. If TRUE (default), the environmental variables are scaled (without centering) before the analysis.

pval_threshold

Numeric. P-value cutoff (after p_adjust_method) to draw only the significant environmental variables. Default 0.05.

p_adjust_method

Character. Multiple-testing correction for the vegan::envfit() p-values of the environmental variables, any method of stats::p.adjust(). Default "none" (raw p-values), the usual choice with few variables.

show_all_env_vectors

Logical. If TRUE, all the environmental variables are drawn, significant or not. Default FALSE.

analysis

Constrained ordination method: "CCA" (default, Canonical Correspondence Analysis) or "RDA" (Redundancy Analysis). Case-insensitive.

scale_arrows

Numeric. Multiplies the length of the environmental arrows; it only changes how they are drawn. Default 1.

title

Character. Plot title. "auto" (default) shows "CCA Biplot" or "RDA Biplot"; NULL shows no title; any other text is used as the title.

save_table

Logical. If TRUE, saves the sample scores and environmental vector loadings (one table, with a type column: "site" or "vector") as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "cca_rda_scores.txt".

Details

The p-values of the environmental vectors come from vegan::envfit() permutations; call set.seed() before the function to make them reproducible.

Value

A ggplot object with the biplot. The axis titles show the percentage of the variance (inertia) explained by each constrained axis.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

# The environmental variables are columns of metadata, chosen with env_vars
cca_rda_biplot(
    table                = table,
    metadata             = metadata,
    env_vars             = c("pH", "TOC", "FW", "Root_FW", "DW"),
    analysis             = "RDA",
    show_all_env_vectors = TRUE,
    group_col            = "Location"
)

Collapse table

Description

Collapses an abundance table to a taxonomic level (e.g. genus, family, phylum), summing the counts of the features that share the same taxonomy. Features not resolved to that level keep their deepest assigned rank and are also summed when they share the same taxonomy. Optionally converts the counts to relative abundance and saves the collapsed table.

Usage

collapse_table(
  table,
  level = "genus",
  rel_abun = FALSE,
  save_table = FALSE,
  table_filename = "collapsed_table.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings. All the other columns are taken as samples, in the order of the table.

level

Character. Taxonomic level: "kingdom", "phylum", "class", "order", "family", "genus" (default) or "species". Case-insensitive.

rel_abun

Logical. If TRUE, converts the counts to relative abundance (%) per sample. Default FALSE.

save_table

Logical. If TRUE, saves the collapsed table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "collapsed_table.txt".

Value

A list with two elements: collapsed_table (wide format, one row per collapsed taxon) and long_format (the same data pivoted to one row per taxon/sample combination).

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

collapse_table(
    table      = table,
    level      = "genus",
    rel_abun   = FALSE,
    save_table = FALSE
)

Correlation between environmental variables and taxa

Description

Computes the relative abundance of the taxa at a taxonomic level, correlates it with environmental variables, and shows the correlations as a heatmap (tile) or a bubble plot (circle).

Usage

corr_env_abund_plot(
  table,
  env_data = NULL,
  metadata = NULL,
  env_vars = NULL,
  method = "spearman",
  hc.order = TRUE,
  geom = c("tile", "circle"),
  show_labels = TRUE,
  col_palette = NULL,
  diverging_palette = "BuOr",
  invert_axes = TRUE,
  taxonomy_db = "silva",
  level = "genus",
  pval_threshold = NULL,
  p_adjust_method = "BH",
  x_label_angle = 45,
  save_table = FALSE,
  table_filename = "corr.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

env_data

Optional data frame of environmental variables, with row names matching the sample names in table. Default NULL: the variables named in env_vars are taken from metadata. Use it only when the variables are in a separate table.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table). The environmental variables can be columns of metadata (see env_vars).

env_vars

Character vector of environmental variables to include in the correlation analysis (columns of metadata, or of env_data if given). Required when env_data is NULL; with a separate env_data, NULL uses all its variables.

method

Character. Correlation method: "spearman" (default), "pearson" or "kendall".

hc.order

Logical. If TRUE (default), taxa and variables are reordered by hierarchical clustering.

geom

Character. Type of visualization to generate: "tile" (heatmap, default) or "circle" (bubble plot). Case-insensitive.

show_labels

Logical. If TRUE (default), the correlation values are shown.

col_palette

Optional character vector of colors for the correlation scale. If NULL (default), diverging_palette is used.

diverging_palette

Character. Colorblind-friendly diverging palette, used when col_palette is NULL: "BuOr" (blue-orange, default), "BuVm" (blue-vermillion), "BuPk" (blue-pink), "GnPk" (green-pink) or "PuYl" (purple-yellow); or "viridis", a sequential scale without a neutral midpoint (not recommended for correlations).

invert_axes

Logical. If TRUE (default), taxa and variables swap axes.

taxonomy_db

Character. Database the taxonomy strings come from: "silva" (default), "gg2" (Greengenes2, also "gg"), "unite" or "Kraken2" (also "kraken"). Case-insensitive.

level

Character. Taxonomic level: "kingdom", "phylum", "class", "order", "family", "genus" (default) or "species". Case-insensitive.

pval_threshold

Numeric or NULL. P-value cutoff (after p_adjust_method) to keep only taxa with a significant correlation with at least one variable. Default NULL (no filtering).

p_adjust_method

Character. Multiple-testing correction for the p-values of all taxon x variable correlations, any method of stats::p.adjust(). Default "BH"; "none" uses the raw p-values.

x_label_angle

Numeric. Rotation (degrees) of the x-axis labels. Default 45; 0 for horizontal labels.

save_table

Logical. If TRUE, saves the plotted correlations (one row per taxon and variable, with the raw and adjusted p-values) as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "corr.txt".

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

corr_env_abund_plot(
    table = table,
    metadata = metadata,
    env_vars = c("pH", "TOC", "FW", "Root_FW", "DW", "Root_L", "Stem_L"),
    method = "pearson",
    geom = "tile",
    hc.order = FALSE,
    invert_axes = TRUE,
    show_labels = FALSE,
    level = "phylum",
    taxonomy_db = "silva"
)

Convert a phyloseq object to MicroBioMeta tables

Description

Extracts the count table, taxonomy and sample metadata of a phyloseq object into the plain data frames that every MicroBioMeta function takes.

Usage

from_phyloseq(physeq)

Arguments

physeq

A phyloseq object with an OTU table and a taxonomy table and sample data.

Value

A list with two data frames:

table

Taxa in rows, samples in columns, and a last column taxonomy with the full taxonomic string (e.g. "k__Bacteria; p__Firmicutes; c__Bacilli").

metadata

Sample metadata whose first column, SAMPLEID, holds the sample names of table.

See Also

from_tse for (Tree)SummarizedExperiment objects.

Examples

if (requireNamespace("phyloseq", quietly = TRUE)) {
    counts <- matrix(c(10, 0, 5, 3, 8, 1),
        nrow = 3,
        dimnames = list(c("ASV1", "ASV2", "ASV3"), c("S1", "S2"))
    )
    tax <- matrix(
        c(
            "Bacteria", "Bacteria", "Bacteria",
            "Firmicutes", "Proteobacteria", NA
        ),
        nrow = 3, dimnames = list(rownames(counts), c("Kingdom", "Phylum"))
    )
    samples <- data.frame(
        Soil = c("Rhizosphere", "Bulk soil"),
        row.names = c("S1", "S2")
    )
    ps <- phyloseq::phyloseq(
        phyloseq::otu_table(counts, taxa_are_rows = TRUE),
        phyloseq::tax_table(tax),
        phyloseq::sample_data(samples)
    )
    mbm <- from_phyloseq(ps)
    mbm$table
    mbm$metadata
}

Convert a (Tree)SummarizedExperiment object to MicroBioMeta tables

Description

Extracts one assay (the counts), the taxonomy (rowData) and the sample metadata (colData) of a TreeSummarizedExperiment or any other SummarizedExperiment, e.g. one built with the mia package, into the plain data frames that every MicroBioMeta function takes.

Usage

from_tse(tse, assay_name = "counts")

Arguments

tse

A TreeSummarizedExperiment or SummarizedExperiment object with taxa in rows and samples in columns.

assay_name

Character. Name of the assay with the counts. Default "counts".

Value

A list with two data frames:

table

Taxa in rows, samples in columns, and a last column taxonomy with the full taxonomic string (e.g. "k__Bacteria; p__Firmicutes; c__Bacilli").

metadata

Sample metadata whose first column, SAMPLEID, holds the sample names of table.

The taxonomy is built from the rowData columns named after taxonomic ranks (Kingdom or Domain, Phylum, Class, Order, Family, Genus, Species; any case). If rowData already has a taxonomy column, it is used as is.

See Also

from_phyloseq for phyloseq objects.

Examples

if (requireNamespace("SummarizedExperiment", quietly = TRUE)) {
    counts <- matrix(c(10, 0, 5, 3, 8, 1),
        nrow = 3,
        dimnames = list(c("ASV1", "ASV2", "ASV3"), c("S1", "S2"))
    )
    tax <- data.frame(
        Kingdom = "Bacteria",
        Phylum = c("Firmicutes", "Proteobacteria", NA),
        row.names = rownames(counts)
    )
    samples <- data.frame(
        Soil = c("Rhizosphere", "Bulk soil"),
        row.names = c("S1", "S2")
    )
    se <- SummarizedExperiment::SummarizedExperiment(
        assays = list(counts = counts), rowData = tax, colData = samples
    )
    mbm <- from_tse(se)
    mbm$table
    mbm$metadata
}

Merge feature table and taxonomy

Description

This function joins a feature table (counts per sample) with the corresponding taxonomy data.

Usage

merge_feature_taxonomy(
  table,
  taxonomy,
  save_table = FALSE,
  table_filename = "merged_feature_taxonomy.txt"
)

Arguments

table

A data frame with features in rows and samples in columns. Row names must hold the feature IDs (OTUs, ASVs, species...). If the table has no row names (e.g. read without row.names = 1), its first column is used as feature IDs.

taxonomy

A data frame or matrix with the taxonomy. Row names (or, if absent, the first column) must hold the feature IDs of table. Features are matched by ID, so both inputs can be in any order.

save_table

Logical. If TRUE, saves the merged table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "merged_feature_taxonomy.txt".

Value

A data frame with the counts of table and the taxonomy columns. A single taxonomy column is renamed to taxonomy.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
full_table <- read.delim(table_path, row.names = 1, check.names = FALSE)

feature_table <- full_table[, setdiff(colnames(full_table), "taxonomy")]
taxonomy_df <- full_table[, "taxonomy", drop = FALSE]

merged <- merge_feature_taxonomy(
    table    = feature_table,
    taxonomy = taxonomy_df
)

Random forest feature importance plot

Description

Fits a random forest (randomForest) that predicts a metadata variable from the abundances, and plots the most important features as a lollipop plot colored by phylum.

Usage

random_forest_lollipop_plot(
  table,
  metadata,
  top_n = 15,
  size = 8,
  variable_to_predict,
  group_colors = NULL,
  title = NULL,
  save_table = FALSE,
  table_filename = "randomforest_importance.txt",
  x_axis_title = "Feature importance (MeanDecreaseGini)"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

top_n

Integer. Number of most important features to show. Default 15.

size

Numeric. Size of the lollipop points. Default 8.

variable_to_predict

Character. Name of the column in metadata to predict (a categorical variable).

group_colors

Optional character vector of colors, one per phylum (recycled if shorter). If NULL (default), the package palette is used.

title

Character. Plot title. NULL (default) shows no title.

save_table

Logical. If TRUE, saves the feature-importance table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "randomforest_importance.txt".

x_axis_title

Character. Title of the x-axis (feature importance). Default "Feature importance (MeanDecreaseGini)".

Details

The random forest is random; call set.seed() before the function to make the result reproducible.

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

random_forest_lollipop_plot(
    table               = table,
    metadata            = metadata,
    variable_to_predict = "Location",
    top_n               = 20,
    size                = 6
)

Compare taxon abundance ratios between two conditions

Description

Computes relative abundances from a taxonomic abundance table and compares two experimental conditions by calculating a directional abundance ratio for each taxon.

Usage

ratios_bubble_plot(
  table,
  metadata,
  group_col,
  condition_A,
  condition_B,
  taxonomy_db = "silva",
  top_n = 30,
  level = "genus",
  x_axis_title = "Taxon",
  legend_title = NULL,
  group_colors = NULL,
  save_table = FALSE,
  table_filename = "ratios_bubble_table.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

group_col

Character. Name of the column in metadata that defines the groups. condition_A and condition_B are two of its values.

condition_A

Character. Name of the first condition to compare.

condition_B

Character. Name of the second condition to compare.

taxonomy_db

Character. Database the taxonomy strings come from: "silva" (default), "gg2" (Greengenes2, also "gg"), "unite" or "Kraken2" (also "kraken"). Case-insensitive.

top_n

Integer. Number of taxa with the highest mean abundance to show. Default 30.

level

Character. Taxonomic level: "kingdom", "phylum", "class", "order", "family", "genus" (default) or "species". Case-insensitive.

x_axis_title

Character. Title of the x-axis (taxon names). Default "Taxon".

legend_title

Character. Title of the legend and of the axis showing the dominant condition. If NULL (default), the name of group_col is used.

group_colors

Optional character vector of two colors, one per condition. If NULL (default), the package's orange/blue pair is used.

save_table

Logical. If TRUE, saves the ratio table as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "ratios_bubble_table.txt".

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

ratios_bubble_plot(
    table = table,
    metadata = metadata,
    group_col = "Location",
    condition_A = "Rhizosphere",
    condition_B = "Roots",
    taxonomy_db = "silva",
    level = "genus",
    top_n = 20
)

Venn diagram of taxa shared between sample groups

Description

Creates a Venn diagram of the taxa shared between groups of samples, with ggvenn or ggVennDiagram.

Usage

venn_plot(
  table,
  metadata,
  merge_by,
  selected_samples = NULL,
  min_prevalence = 0,
  title = NULL,
  method = "ggvenn",
  group_colors = NULL,
  save_table = FALSE,
  table_filename = "venn_taxa_sets.txt"
)

Arguments

table

A data frame with taxa in rows and samples in columns. The last column must be named taxonomy, containing full taxonomic strings.

metadata

A data frame containing sample metadata. Its first column must hold the sample IDs (the column names of table).

merge_by

Character. Name of the column in metadata that defines the groups (one set of taxa per group).

selected_samples

Optional character vector of the sample IDs to use. If NULL (default), all samples are used.

min_prevalence

Numeric (0-1). Minimum fraction of the samples of a group where a taxon must be present to count it in that group. Default 0 (present in at least one sample).

title

Character. Plot title. NULL (default) shows no title.

method

Character. Package used to draw the Venn diagram: "ggvenn" (default) or "ggVennDiagram". Case-insensitive.

group_colors

Optional character vector of colors, one per group, named after the groups or in their order. If NULL (default), the colorblind-friendly Okabe-Ito palette is used.

save_table

Logical. If TRUE, saves the taxa of each group (long format) as a tab-delimited file. Default FALSE.

table_filename

Character. Name or path of the saved file (used when save_table = TRUE). Default "venn_taxa_sets.txt".

Value

A ggplot object.

Examples

table_path <- system.file("extdata", "subset_table_bacteria.txt", package = "MicroBioMeta")
table <- read.delim(table_path, row.names = 1, check.names = FALSE)

metadata_path <- system.file("extdata", "subset_metadata_bacteria.txt", package = "MicroBioMeta")
metadata <- read.delim(metadata_path, check.names = FALSE)

venn_plot(
    table          = table,
    metadata       = metadata,
    merge_by       = "Location",
    min_prevalence = 0
)

## Filtering taxa by prevalence
venn_plot(
    table          = table,
    metadata       = metadata,
    merge_by       = "Location",
    min_prevalence = 0.2
)

## Custom colors
venn_plot(
    table          = table,
    metadata       = metadata,
    merge_by       = "Location",
    min_prevalence = 0,
    group_colors   = c("#1B9E77", "#D95F02")
)