trans_phylo: trans_phylo class

trans_phyloR Documentation

trans_phylo class

Description

Publication-grade phylogenetic tree visualization built on ggtree package (DOI: 10.1002/imt2.56), designed for the microtable object. Supports group-based branch/tip coloring (with full clade coloring via groupOTU) and multi-layer outer ring annotations.

Methods

Public methods


Method new()

Initialize a trans_phylo object

Usage
trans_phylo$new(
  dataset,
  group_col = "Phylum",
  ring_data = NULL,
  color_palette = NULL,
  group_prefix = NULL,
  group_prefix_remove = NULL,
  clade_coloring = TRUE
)
Arguments
dataset

microtable object containing phylo_tree and tax_table

group_col

string, taxonomic rank column in tax_table for branch/tip coloring, default "Phylum"

ring_data

data.frame, outer ring annotation data; row names or first column should match tip labels. Supports numeric (heatmap) and categorical (color band) columns

color_palette

vector, optional custom color palette; If the color vector has names, they will be used in correspondence with the names; auto-generated if NULL

group_prefix

string, prefix to add to group names for legend display

group_prefix_remove

string, prefix to strip from group names (e.g. "p__")

clade_coloring

logical, if TRUE (default), propagate group info to internal nodes via groupOTU so that entire clades are colored; if FALSE, groupOTU is not applied and branch_color_by_group is automatically set to FALSE in plot_tree() (since ggtree's stat_tree() requires groupOTU-annotated data for branch coloring). Tip points are still colored by group via the fill aesthetic regardless.

Examples
\dontrun{
library(microeco)
library(magrittr)

mt <- clone(dataset)
mt200 <- clone(mt)

# Subset to top 200 OTUs
top_otus <- names(sort(mt200$taxa_sums(), decreasing = TRUE))[1:200]
mt200$otu_table %<>% .[top_otus, , drop = FALSE]
mt200$tidy_dataset()

# ========================================================================
# Build rich ring annotation data
# ========================================================================

otu <- mt200$otu_table
tax <- mt200$tax_table
si  <- mt200$sample_table
n_otus <- nrow(otu)

# Relative abundance (mean %)
total_rel_abund <- trans_norm$new(mt)$norm(method = "TSS")$otu_table
rel_abund   <- total_rel_abund[rownames(otu), ]
mean_abund  <- rowMeans(rel_abund) * 100

# Prevalence (% of samples where detected)
prevalence <- rowMeans(otu > 0) * 100

# Log10 abundance
log_abund <- log10(rowMeans(otu) + 1)

# ---- Simulated ecological indicators ----
# Importance index: composite of abundance and prevalence
# (mimics indicators like indicator species analysis or random forest importance)
importance_raw <- mean_abund * sqrt(prevalence / 100)
importance <- round(importance_raw / max(importance_raw, na.rm = TRUE) * 100, 2)

# Specificity: how concentrated is an OTU in its preferred habitat
# (low = generalist, high = specialist)
niche <- trans_niche$new(mt)$cal_niche_breadth()
specificity <- 1 - niche$res_niche_breadth[rownames(otu), "Levins_Standardized"]

# network metrics example
net <- trans_network$new(mt, cor_method = "pearson")$cal_network()$get_node_table()
centrality <- net$res_node_table[rownames(otu), "closeness_centrality"]
connectivity <- net$res_node_table[rownames(otu), "z"]

# Habitat
mt$add_rownames2tax("OTU")
mt$cal_abund()
# Wilcoxon test + Random forest to obtain habitats of differential OTUs
mt_diff <- trans_diff$new(dataset = mt, method = "rf", taxa_level = "OTU", group = "Group")
mt_diff_res <- mt_diff$res_diff 
rownames(mt_diff_res) %<>% gsub(".*\\|", "", .)
dominant_habitat <- mt_diff_res[rownames(otu), "Group"]

# Class taxonomy
class_col <- if ("Class" %in% colnames(tax)) tax$Class else rep("Unknown", n_otus)

# Assemble ring data
ring_df <- data.frame(
  label        = rownames(otu),
  RelAbund     = round(mean_abund, 4),
  Prevalence   = round(prevalence, 1),
  LogAbund     = round(log_abund, 3),
  Importance   = importance,
  Specificity  = specificity,
  Centrality   = centrality,
  Connectivity = connectivity,
  Habitat      = dominant_habitat,
  Class        = class_col,
  stringsAsFactors = FALSE
)

# Clean Class column
ring_df$Class <- gsub("^c__", "", ring_df$Class)
ring_df$Class[ring_df$Class == "" | is.na(ring_df$Class)] <- "Unclassified"

pviz <- trans_phylo$new(
  dataset             = mt,
  group_col           = "Phylum",
  group_prefix_remove = "p__",
  ring_data           = ring_df,
  clade_coloring      = TRUE
)
}

Method plot_tree()

Draw a phylogenetic tree (publication grade)

Usage
trans_phylo$plot_tree(
  layout = "fan",
  open_angle = 30,
  branch_size = 0.3,
  tip_point = TRUE,
  tip_point_size = 2,
  tip_point_shape = 21,
  tip_point_stroke = 0.3,
  tip_point_alpha = 0.9,
  show_tip_label = FALSE,
  tip_label_size = 2,
  tip_label_offset = 0.5,
  show_node_label = FALSE,
  branch_color_by_group = TRUE,
  branch_color = "grey40",
  legend_title = NULL,
  legend_position = "right",
  legend_font_size = 3.5,
  theme_base = NULL
)
Arguments
layout

tree layout: "fan", "circular", "radial", or "rectangular", default "fan"

open_angle

numeric, opening angle of the fan (0-360), default 30 (fan/circular only)

branch_size

branch line width, default 0.3

tip_point

logical, whether to show tip points, default TRUE

tip_point_size

tip point size, default 2

tip_point_shape

tip point shape, default 21 (filled circle with border)

tip_point_stroke

tip point border width, default 0.3

tip_point_alpha

tip point transparency, default 0.9

show_tip_label

logical, whether to show tip labels, default FALSE

tip_label_size

tip label font size, default 2

tip_label_offset

tip label offset, default 0.5

show_node_label

logical, whether to show internal node labels, default FALSE

branch_color_by_group

logical, color branches by group, default TRUE

branch_color

unified branch color (when branch_color_by_group = FALSE), default "grey40"

legend_title

legend title, default uses group_col

legend_position

legend position, default "right"

legend_font_size

legend font size, default 3.5

theme_base

base theme, default ggtree::theme_tree2()

Returns

ggtree plot object

Examples
\dontrun{
pviz$plot_tree(
  layout             = "fan",
  open_angle         = 18,
  branch_size        = 0.15,
  tip_point          = TRUE,
  tip_point_size     = 1.2,
  tip_point_shape    = 21,
  tip_point_stroke   = 0.1,
  tip_point_alpha    = 0.80,
  legend_title       = "Phylum"
)
}

Method add_ring()

Add one outer ring annotation layer to the current plot. Extra arguments (...) are passed to ggtreeExtra::geom_fruit() for advanced customization (e.g. axis.params, grid.params, direction).

Usage
trans_phylo$add_ring(
  col_name,
  ring_data = NULL,
  color_low = "#0D0887",
  color_high = "#F0F921",
  limits = NULL,
  categorical_colors = NULL,
  ring_width = NULL,
  ring_offset = NULL,
  ring_gap = 0.03,
  ring_offset_first = 0.02,
  ring_width_bar = 0.03,
  ring_width_other = 0.03,
  show_legend = TRUE,
  legend_title_custom = NULL,
  ring_label = NULL,
  geom = "bar",
  na_fill = "grey90",
  na_replace = "Unknown",
  point_size = 1.5,
  ...
)
Arguments
col_name

string, column name from ring_data to display

ring_data

optional custom data.frame for this ring (overrides self$ring_data)

color_low

color for low numeric values, default "#0D0887"

color_high

color for high numeric values, default "#F0F921"

limits

numeric vector of length 2, explicit limits for the fill scale; default NULL means auto from data range

categorical_colors

color vector or palette function for categorical columns, default NULL (auto). If a named character vector, names must correspond to factor levels present in the data. If an unnamed character vector, it is recycled and named by the factor levels in their alphabetical order. If a palette function (e.g. scales::hue_pal() or colorRampPalette(c(...))), it is invoked with the number of factor levels to produce a color vector, which is then named by the levels.

ring_width

ring width, default NULL; see ring_width_bar and ring_width_other

ring_offset

ring offset, default NULL; If NULL, ring_offset_first + ring_gap

ring_gap

numeric, gap between consecutive rings when ring_offset is not manually specified

ring_offset_first

numeric, starting offset for the very first ring when ring_offset is not manually specified

ring_width_bar

numeric, default ring width for numeric bar-type rings when ring_width is NULL

ring_width_other

numeric, default ring width for non-bar rings (categorical color band, point, star) when ring_width is NULL

show_legend

logical, whether to show this ring's legend, default TRUE

legend_title_custom

custom legend title, default uses column name

ring_label

label around the ring, default uses column name

geom

type: "bar" for bar heatmap, "point" for scatter, "star" for stars; categorical columns automatically use color band regardless of this setting

na_fill

fill color for NA values, default "grey90"

na_replace

categorical value to replace NA/empty with, default "Unknown". Only applied when categorical_colors is NULL (auto palette). Set to NULL to keep NA values as NA, in which case they are colored with na_fill via scale_fill_manual(na.value = na_fill). When categorical_colors is provided, NA is always kept as NA and colored with na_fill (regardless of na_replace), so the user's color vector does not need to cover an extra "Unknown" level.

point_size

point size (only for geom = "point"), default 1.5

...

additional arguments passed to ggtreeExtra::geom_fruit() (e.g. axis.params, grid.params)

Returns

updated ggtree plot object

Examples
\dontrun{
# Numeric bar ring
pviz$add_ring(
  col_name            = "LogAbund",
  geom                = "bar",
  ring_width          = 0.03,
  ring_offset         = 0.02,
  color_low           = "#440154",
  color_high          = "#FDE725",
  na_fill             = "grey95",
  legend_title_custom = "Log10\\nAbund."
)

# Categorical color band ring
pviz$add_ring(
  col_name            = "Habitat",
  na_fill             = "grey95",
  legend_title_custom = "Habitat",
  categorical_colors  = c("IW" = "#E64B35", "CW" = "#4DBBD5", "TW" = "#00A087")
)
}

Method add_ring_labels()

Automatically place text labels for all added rings at the edge of the fan opening. Uses the ring geometry history recorded by add_ring() to compute positions. Call AFTER all add_ring() calls and AFTER add_spacer().

Usage
trans_phylo$add_ring_labels(size = 1.8, color = "grey25", angle_offset = 15)
Arguments
size

text font size, default 1.8

color

text color, default "grey25"

angle_offset

numeric, fine-tuning angle padding inside the opening gap, default 2 (degrees)

fontface

text font style, default "italic"

Returns

updated ggtree plot object

Examples
\dontrun{
pviz$add_ring_labels(size = 1.8, color = "grey25")
}

Method add_rings_batch()

Batch add all (or selected) columns from ring_data as outer rings. Parameters ring_width, ring_offset, numeric_geom and show_legend support vector input (length = number of col_names); a single value is recycled for all rings. color_low and color_high are aligned positionally to NUMERIC columns only (length = number of numeric columns; non-numeric columns are passed NULL). categorical_palette is aligned to NON-NUMERIC columns only (numeric columns passed NULL): a single value or unnamed list is recycled to the number of categorical columns; a named list is matched by column name.

Usage
trans_phylo$add_rings_batch(
  col_names = NULL,
  numeric_geom = "bar",
  ring_width = 0.05,
  ring_offset = 0.03,
  color_low = "#0D0887",
  color_high = "#F0F921",
  categorical_palette = NULL,
  show_legend = TRUE,
  ...
)
Arguments
col_names

character vector of column names to add; NULL means all columns

numeric_geom

character or character vector; geom type(s) for numeric columns, default "bar". Recycled if length 1; must match length of col_names otherwise.

ring_width

numeric or numeric vector; ring width(s), default 0.05. Single value is recycled; vector must match length of col_names.

ring_offset

numeric or numeric vector; gap(s) before each ring, default 0.03. Single value is recycled; vector must match length of col_names.

color_low

character or character vector; color(s) for low numeric values, default "#0D0887". Aligned positionally to NUMERIC columns only and recycled to the number of numeric columns; non-numeric columns are passed NULL (their colors come from categorical_palette). A single value is recycled for all numeric columns.

color_high

character or character vector; color(s) for high numeric values, default "#F0F921". Aligned positionally to NUMERIC columns only and recycled to the number of numeric columns; non-numeric columns are passed NULL. A single value is recycled for all numeric columns.

categorical_palette

palette function, named color vector, or list thereof, for categorical columns. Aligned to NON-NUMERIC (categorical) columns only: a single value is recycled for all categorical columns; an unnamed list is recycled positionally to the number of categorical columns; a NAMED list is matched to columns by name (e.g. list(Habitat = c(...), Salinity = c(...))). Numeric columns are always passed NULL. Columns without a matching entry fall back to auto-generated colors. Each entry may be either a palette function (e.g. scales::hue_pal() or colorRampPalette(c(...))) or a named color vector. Forwarded to each add_ring() call as categorical_colors. Default NULL.

show_legend

logical or logical vector; whether to show legends, default TRUE. Single value is recycled; vector must match length of col_names.

...

additional arguments passed to each add_ring() call

Returns

updated ggtree plot object

Examples
\dontrun{
pviz$add_rings_batch(
  col_names    = c("RelAbund", "Prevalence", "Habitat"),
  numeric_geom = "bar",
  ring_width   = c(0.02, 0.03, 0.04),
  ring_offset  = c(0.03, 0.02, 0.03),
  color_low    = c("#440154", "#EDF8FB"),
  color_high   = c("#FDE725", "#006D2C"),
  categorical_palette = list(Habitat = c("IW" = "red", "CW" = "blue", "TW" = "green")),
  show_legend  = TRUE
)
}

Method add_scale_bar()

Add an evolutionary distance scale bar to the plot

Usage
trans_phylo$add_scale_bar(
  x = NULL,
  y = NULL,
  label = "0.05",
  fontsize = 2,
  linesize = 0.5,
  offset = 0.3,
  ...
)
Arguments
x

numeric, x coordinate

y

numeric, y coordinate

label

string, scale bar label

fontsize

numeric, default 2, text size

linesize

numeric, default 0.5, line size

offset

numeric, default 0.3, offset of text to line

...

additional arguments passed to ggtree::geom_treescale

Returns

updated plot

Examples
\dontrun{
pviz$add_scale_bar(x = 0.2, y = 0, label = "0.05")
}

Method add_highlight_clade()

Add highlight background to a specified clade

Usage
trans_phylo$add_highlight_clade(
  node,
  fill = "steelblue",
  alpha = 0.3,
  extend = 0.15
)
Arguments
node

node number (can be found in $plot_obj$data)

fill

highlight fill color, default "steelblue"

alpha

transparency, default 0.3

extend

extend amount, default 0.15

Returns

updated plot

Examples
\dontrun{
# Highlight clade at node 150
pviz$add_highlight_clade(node = 150, fill = "steelblue", alpha = 0.3)
}

Method add_clade_label()

Add annotation text to a specified clade

Usage
trans_phylo$add_clade_label(
  node,
  label,
  color = "black",
  size = 4,
  offset = 0.5,
  barsize = 0.8
)
Arguments
node

node number

label

annotation text

color

text color, default "black"

size

text size, default 4

offset

offset amount, default 0.5

barsize

bar thickness, default 0.8

Returns

updated plot

Examples
\dontrun{
pviz$add_clade_label(node = 150, label = "Clade A", color = "black", size = 4)
}

Method theme_publication()

Apply a publication-grade theme to the current plot

Usage
trans_phylo$theme_publication(
  base_size = 12,
  base_family = "sans",
  bg_color = "white"
)
Arguments
base_size

base font size, default 12

base_family

font family, default "sans"

bg_color

background color, default "white"

Returns

updated plot

Examples
\dontrun{
pviz$theme_publication(base_size = 7)
}

Method get_plot()

Return the current ggtree plot object

Usage
trans_phylo$get_plot()
Returns

ggtree / ggplot object

Examples
\dontrun{
p <- pviz$get_plot()
print(p)
}

Method save_plot()

Save the current plot to a file

Usage
trans_phylo$save_plot(
  filename,
  width = 12,
  height = 12,
  dpi = 300,
  device = NULL
)
Arguments
filename

file path; format inferred from extension

width

plot width, default 12

height

plot height, default 12

dpi

resolution, default 300

device

graphics device, default NULL (auto)

Returns

NULL

Examples
\dontrun{
pviz$save_plot(
  filename = "phylo_tree.png",
  width    = 16,
  height   = 16,
  dpi      = 300
)

				
}

Method print()

Print a summary of the trans_phylo object

Usage
trans_phylo$print(...)
Arguments
...

ignored (for compatibility with the generic print method)

Examples
\dontrun{
print(pviz)
}

Method clone()

The objects of this class are cloneable with this method.

Usage
trans_phylo$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples


## ------------------------------------------------
## Method `trans_phylo$new`
## ------------------------------------------------

## Not run: 
library(microeco)
library(magrittr)

mt <- clone(dataset)
mt200 <- clone(mt)

# Subset to top 200 OTUs
top_otus <- names(sort(mt200$taxa_sums(), decreasing = TRUE))[1:200]
mt200$otu_table %<>% .[top_otus, , drop = FALSE]
mt200$tidy_dataset()

# ========================================================================
# Build rich ring annotation data
# ========================================================================

otu <- mt200$otu_table
tax <- mt200$tax_table
si  <- mt200$sample_table
n_otus <- nrow(otu)

# Relative abundance (mean %)
total_rel_abund <- trans_norm$new(mt)$norm(method = "TSS")$otu_table
rel_abund   <- total_rel_abund[rownames(otu), ]
mean_abund  <- rowMeans(rel_abund) * 100

# Prevalence (% of samples where detected)
prevalence <- rowMeans(otu > 0) * 100

# Log10 abundance
log_abund <- log10(rowMeans(otu) + 1)

# ---- Simulated ecological indicators ----
# Importance index: composite of abundance and prevalence
# (mimics indicators like indicator species analysis or random forest importance)
importance_raw <- mean_abund * sqrt(prevalence / 100)
importance <- round(importance_raw / max(importance_raw, na.rm = TRUE) * 100, 2)

# Specificity: how concentrated is an OTU in its preferred habitat
# (low = generalist, high = specialist)
niche <- trans_niche$new(mt)$cal_niche_breadth()
specificity <- 1 - niche$res_niche_breadth[rownames(otu), "Levins_Standardized"]

# network metrics example
net <- trans_network$new(mt, cor_method = "pearson")$cal_network()$get_node_table()
centrality <- net$res_node_table[rownames(otu), "closeness_centrality"]
connectivity <- net$res_node_table[rownames(otu), "z"]

# Habitat
mt$add_rownames2tax("OTU")
mt$cal_abund()
# Wilcoxon test + Random forest to obtain habitats of differential OTUs
mt_diff <- trans_diff$new(dataset = mt, method = "rf", taxa_level = "OTU", group = "Group")
mt_diff_res <- mt_diff$res_diff 
rownames(mt_diff_res) %<>% gsub(".*\\|", "", .)
dominant_habitat <- mt_diff_res[rownames(otu), "Group"]

# Class taxonomy
class_col <- if ("Class" %in% colnames(tax)) tax$Class else rep("Unknown", n_otus)

# Assemble ring data
ring_df <- data.frame(
  label        = rownames(otu),
  RelAbund     = round(mean_abund, 4),
  Prevalence   = round(prevalence, 1),
  LogAbund     = round(log_abund, 3),
  Importance   = importance,
  Specificity  = specificity,
  Centrality   = centrality,
  Connectivity = connectivity,
  Habitat      = dominant_habitat,
  Class        = class_col,
  stringsAsFactors = FALSE
)

# Clean Class column
ring_df$Class <- gsub("^c__", "", ring_df$Class)
ring_df$Class[ring_df$Class == "" | is.na(ring_df$Class)] <- "Unclassified"

pviz <- trans_phylo$new(
  dataset             = mt,
  group_col           = "Phylum",
  group_prefix_remove = "p__",
  ring_data           = ring_df,
  clade_coloring      = TRUE
)

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$plot_tree`
## ------------------------------------------------

## Not run: 
pviz$plot_tree(
  layout             = "fan",
  open_angle         = 18,
  branch_size        = 0.15,
  tip_point          = TRUE,
  tip_point_size     = 1.2,
  tip_point_shape    = 21,
  tip_point_stroke   = 0.1,
  tip_point_alpha    = 0.80,
  legend_title       = "Phylum"
)

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$add_ring`
## ------------------------------------------------

## Not run: 
# Numeric bar ring
pviz$add_ring(
  col_name            = "LogAbund",
  geom                = "bar",
  ring_width          = 0.03,
  ring_offset         = 0.02,
  color_low           = "#440154",
  color_high          = "#FDE725",
  na_fill             = "grey95",
  legend_title_custom = "Log10\\nAbund."
)

# Categorical color band ring
pviz$add_ring(
  col_name            = "Habitat",
  na_fill             = "grey95",
  legend_title_custom = "Habitat",
  categorical_colors  = c("IW" = "#E64B35", "CW" = "#4DBBD5", "TW" = "#00A087")
)

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$add_ring_labels`
## ------------------------------------------------

## Not run: 
pviz$add_ring_labels(size = 1.8, color = "grey25")

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$add_rings_batch`
## ------------------------------------------------

## Not run: 
pviz$add_rings_batch(
  col_names    = c("RelAbund", "Prevalence", "Habitat"),
  numeric_geom = "bar",
  ring_width   = c(0.02, 0.03, 0.04),
  ring_offset  = c(0.03, 0.02, 0.03),
  color_low    = c("#440154", "#EDF8FB"),
  color_high   = c("#FDE725", "#006D2C"),
  categorical_palette = list(Habitat = c("IW" = "red", "CW" = "blue", "TW" = "green")),
  show_legend  = TRUE
)

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$add_scale_bar`
## ------------------------------------------------

## Not run: 
pviz$add_scale_bar(x = 0.2, y = 0, label = "0.05")

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$add_highlight_clade`
## ------------------------------------------------

## Not run: 
# Highlight clade at node 150
pviz$add_highlight_clade(node = 150, fill = "steelblue", alpha = 0.3)

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$add_clade_label`
## ------------------------------------------------

## Not run: 
pviz$add_clade_label(node = 150, label = "Clade A", color = "black", size = 4)

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$theme_publication`
## ------------------------------------------------

## Not run: 
pviz$theme_publication(base_size = 7)

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$get_plot`
## ------------------------------------------------

## Not run: 
p <- pviz$get_plot()
print(p)

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$save_plot`
## ------------------------------------------------

## Not run: 
pviz$save_plot(
  filename = "phylo_tree.png",
  width    = 16,
  height   = 16,
  dpi      = 300
)

				

## End(Not run)

## ------------------------------------------------
## Method `trans_phylo$print`
## ------------------------------------------------

## Not run: 
print(pviz)

## End(Not run)

microeco documentation built on Oct. 20, 2026, 9:06 a.m.