| trans_phylo | R Documentation |
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.
new()Initialize a trans_phylo object
trans_phylo$new( dataset, group_col = "Phylum", ring_data = NULL, color_palette = NULL, group_prefix = NULL, group_prefix_remove = NULL, clade_coloring = TRUE )
datasetmicrotable object containing phylo_tree and tax_table
group_colstring, taxonomic rank column in tax_table for branch/tip coloring, default "Phylum"
ring_datadata.frame, outer ring annotation data; row names or first column should match tip labels. Supports numeric (heatmap) and categorical (color band) columns
color_palettevector, optional custom color palette; If the color vector has names, they will be used in correspondence with the names; auto-generated if NULL
group_prefixstring, prefix to add to group names for legend display
group_prefix_removestring, prefix to strip from group names (e.g. "p__")
clade_coloringlogical, 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.
\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
)
}
plot_tree()Draw a phylogenetic tree (publication grade)
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 )
layouttree layout: "fan", "circular", "radial", or "rectangular", default "fan"
open_anglenumeric, opening angle of the fan (0-360), default 30 (fan/circular only)
branch_sizebranch line width, default 0.3
tip_pointlogical, whether to show tip points, default TRUE
tip_point_sizetip point size, default 2
tip_point_shapetip point shape, default 21 (filled circle with border)
tip_point_stroketip point border width, default 0.3
tip_point_alphatip point transparency, default 0.9
show_tip_labellogical, whether to show tip labels, default FALSE
tip_label_sizetip label font size, default 2
tip_label_offsettip label offset, default 0.5
show_node_labellogical, whether to show internal node labels, default FALSE
branch_color_by_grouplogical, color branches by group, default TRUE
branch_colorunified branch color (when branch_color_by_group = FALSE), default "grey40"
legend_titlelegend title, default uses group_col
legend_positionlegend position, default "right"
legend_font_sizelegend font size, default 3.5
theme_basebase theme, default ggtree::theme_tree2()
ggtree plot object
\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"
)
}
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).
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, ... )
col_namestring, column name from ring_data to display
ring_dataoptional custom data.frame for this ring (overrides self$ring_data)
color_lowcolor for low numeric values, default "#0D0887"
color_highcolor for high numeric values, default "#F0F921"
limitsnumeric vector of length 2, explicit limits for the fill scale; default NULL means auto from data range
categorical_colorscolor 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_widthring width, default NULL; see ring_width_bar and ring_width_other
ring_offsetring offset, default NULL; If NULL, ring_offset_first + ring_gap
ring_gapnumeric, gap between consecutive rings when ring_offset is not manually specified
ring_offset_firstnumeric, starting offset for the very first ring when ring_offset is not manually specified
ring_width_barnumeric, default ring width for numeric bar-type rings when ring_width is NULL
ring_width_othernumeric, default ring width for non-bar rings (categorical color band, point, star) when ring_width is NULL
show_legendlogical, whether to show this ring's legend, default TRUE
legend_title_customcustom legend title, default uses column name
ring_labellabel around the ring, default uses column name
geomtype: "bar" for bar heatmap, "point" for scatter, "star" for stars; categorical columns automatically use color band regardless of this setting
na_fillfill color for NA values, default "grey90"
na_replacecategorical 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_sizepoint size (only for geom = "point"), default 1.5
...additional arguments passed to ggtreeExtra::geom_fruit() (e.g. axis.params, grid.params)
updated ggtree plot object
\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")
)
}
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().
trans_phylo$add_ring_labels(size = 1.8, color = "grey25", angle_offset = 15)
sizetext font size, default 1.8
colortext color, default "grey25"
angle_offsetnumeric, fine-tuning angle padding inside the opening gap, default 2 (degrees)
fontfacetext font style, default "italic"
updated ggtree plot object
\dontrun{
pviz$add_ring_labels(size = 1.8, color = "grey25")
}
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.
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, ... )
col_namescharacter vector of column names to add; NULL means all columns
numeric_geomcharacter or character vector; geom type(s) for numeric columns, default "bar". Recycled if length 1; must match length of col_names otherwise.
ring_widthnumeric or numeric vector; ring width(s), default 0.05. Single value is recycled; vector must match length of col_names.
ring_offsetnumeric or numeric vector; gap(s) before each ring, default 0.03. Single value is recycled; vector must match length of col_names.
color_lowcharacter 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_highcharacter 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_palettepalette 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_legendlogical 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
updated ggtree plot object
\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
)
}
add_scale_bar()Add an evolutionary distance scale bar to the plot
trans_phylo$add_scale_bar( x = NULL, y = NULL, label = "0.05", fontsize = 2, linesize = 0.5, offset = 0.3, ... )
xnumeric, x coordinate
ynumeric, y coordinate
labelstring, scale bar label
fontsizenumeric, default 2, text size
linesizenumeric, default 0.5, line size
offsetnumeric, default 0.3, offset of text to line
...additional arguments passed to ggtree::geom_treescale
updated plot
\dontrun{
pviz$add_scale_bar(x = 0.2, y = 0, label = "0.05")
}
add_highlight_clade()Add highlight background to a specified clade
trans_phylo$add_highlight_clade( node, fill = "steelblue", alpha = 0.3, extend = 0.15 )
nodenode number (can be found in $plot_obj$data)
fillhighlight fill color, default "steelblue"
alphatransparency, default 0.3
extendextend amount, default 0.15
updated plot
\dontrun{
# Highlight clade at node 150
pviz$add_highlight_clade(node = 150, fill = "steelblue", alpha = 0.3)
}
add_clade_label()Add annotation text to a specified clade
trans_phylo$add_clade_label( node, label, color = "black", size = 4, offset = 0.5, barsize = 0.8 )
nodenode number
labelannotation text
colortext color, default "black"
sizetext size, default 4
offsetoffset amount, default 0.5
barsizebar thickness, default 0.8
updated plot
\dontrun{
pviz$add_clade_label(node = 150, label = "Clade A", color = "black", size = 4)
}
theme_publication()Apply a publication-grade theme to the current plot
trans_phylo$theme_publication( base_size = 12, base_family = "sans", bg_color = "white" )
base_sizebase font size, default 12
base_familyfont family, default "sans"
bg_colorbackground color, default "white"
updated plot
\dontrun{
pviz$theme_publication(base_size = 7)
}
get_plot()Return the current ggtree plot object
trans_phylo$get_plot()
ggtree / ggplot object
\dontrun{
p <- pviz$get_plot()
print(p)
}
save_plot()Save the current plot to a file
trans_phylo$save_plot( filename, width = 12, height = 12, dpi = 300, device = NULL )
filenamefile path; format inferred from extension
widthplot width, default 12
heightplot height, default 12
dpiresolution, default 300
devicegraphics device, default NULL (auto)
NULL
\dontrun{
pviz$save_plot(
filename = "phylo_tree.png",
width = 16,
height = 16,
dpi = 300
)
}
print()Print a summary of the trans_phylo object
trans_phylo$print(...)
...ignored (for compatibility with the generic print method)
\dontrun{
print(pviz)
}
clone()The objects of this class are cloneable with this method.
trans_phylo$clone(deep = FALSE)
deepWhether to make a deep clone.
## ------------------------------------------------
## 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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.