### Install linkET from GitHub Source: https://github.com/hy4m/linket/blob/master/README.md Installs the linkET package from GitHub. Ensure devtools is installed first. ```r # install.packages("devtools") devtools::install_github("Hy4m/linkET", force = TRUE) packageVersion("linkET") ``` -------------------------------- ### Get Mantel colour palette with color_pal() Source: https://context7.com/hy4m/linket/llms.txt Generates qualitative colours for encoding p-value or r-value categories, suitable for geom_couple(). Includes grey for non-significant values. ```r color_pal(3) # 3 colours: orange, teal, grey #> [1] "#D95F02" "#1B9E77" "#CCCCCC99" ``` ```r color_pal(4, alpha = 0.8) ``` ```r # Typical use inside geom_couple() scale_colour_manual(values = color_pal(3)) ``` -------------------------------- ### Initialize ggplot Heatmap with hyplot() Source: https://context7.com/hy4m/linket/llms.txt Creates a base ggplot coordinate system for matrix data, setting reversed y-axis and square x-axis. Requires 'ggplot2'. ```r library(ggplot2) # Simple tile heatmap from raw data hyplot(mtcars) + geom_tile(aes(fill = mtcars)) ``` ```r # Upper-triangular heatmap with correlation data correlate(mtcars) %>% as_matrix_data(type = "upper", diag = FALSE) %>% hyplot() + geom_square() ``` ```r # Grouped / faceted heatmap correlate(mtcars, group = rep(c("A","B"), 16)) %>% as_matrix_data() %>% hyplot() + geom_square() ``` -------------------------------- ### Create Basic Heatmap with hyplot and geom_tile Source: https://github.com/hy4m/linket/blob/master/README.md Generates a basic heatmap visualization using the hyplot function with geom_tile. Requires ggplot2. ```r library(ggplot2) matrix_data(list(mtcars = mtcars)) %>% hyplot(aes(fill = mtcars)) + geom_tile() ``` -------------------------------- ### Quick Correlation Plot with qcorrplot() Source: https://context7.com/hy4m/linket/llms.txt A wrapper around hyplot() for correlation objects, automatically mapping aesthetics and setting coordinate systems. Accepts various correlation input types. ```r library(ggplot2) # Full matrix with square markers qcorrplot(correlate(mtcars)) + geom_square() ``` ```r # Lower triangular, no diagonal, custom grid colour qcorrplot(correlate(mtcars), type = "lower", diag = FALSE, grid_col = "grey80") + geom_square() + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu")) ``` ```r # Upper triangular with significance marks qcorrplot(correlate(mtcars), type = "upper") + geom_square() + geom_mark() ``` -------------------------------- ### Perform Mantel Test and Visualize Results in R Source: https://github.com/hy4m/linket/blob/master/README.md This snippet demonstrates how to perform a mantel test using vegan and visualize the results with qcorrplot. It includes data loading, mantel test execution with subsetting, and plot customization with manual scaling for size and color. ```r library(dplyr) #> #> 载入程辑包:'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union data("varechem", package = "vegan") data("varespec", package = "vegan") mantel <- mantel_test(varespec, varechem, spec_select = list(Spec01 = 1:7, Spec02 = 8:18, Spec03 = 19:37, Spec04 = 38:44)) %>% mutate(rd = cut(r, breaks = c(-Inf, 0.2, 0.4, Inf), labels = c("< 0.2", "0.2 - 0.4", ">= 0.4")), pd = cut(p, breaks = c(-Inf, 0.01, 0.05, Inf), labels = c("< 0.01", "0.01 - 0.05", ">= 0.05"))) #> `mantel_test()` using 'bray' dist method for 'spec'. #> `mantel_test()` using 'euclidean' dist method for 'env'. qcorrplot(correlate(varechem), type = "lower", diag = FALSE) + geom_square() + geom_couple(aes(colour = pd, size = rd), data = mantel, curvature = nice_curvature()) + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu")) + scale_size_manual(values = c(0.5, 1, 2)) + scale_colour_manual(values = color_pal(3)) + guides(size = guide_legend(title = "Mantel's r", override.aes = list(colour = "grey35"), order = 2), colour = guide_legend(title = "Mantel's p", override.aes = list(size = 3), order = 1), fill = guide_colorbar(title = "Pearson's r", order = 3)) ``` -------------------------------- ### hyplot() — General matrix heatmap initialiser Source: https://context7.com/hy4m/linket/llms.txt Creates the base ggplot coordinate system for any matrix_data or md_tbl object. Sets reversed y-axis, square x-axis, and applies theme_hy(). All subsequent geom layers are added with +. ```APIDOC ## hyplot() ### Description Creates the base ggplot coordinate system for any `matrix_data` or `md_tbl` object. Sets reversed y-axis, square x-axis, and applies `theme_hy()`. All subsequent geom layers are added with `+`. ### Method `hyplot(matrix_data, ...)` ### Parameters #### Arguments - **matrix_data**: A matrix or data frame. - **...**: Additional arguments passed to `ggplot()`. ### Request Example ```r library(ggplot2) # Simple tile heatmap from raw data hyplot(mtcars) + geom_tile(aes(fill = mtcars)) # Upper-triangular heatmap with correlation data correlate(mtcars) %>% as_matrix_data(type = "upper", diag = FALSE) %>% hyplot() + geom_square() # Grouped / faceted heatmap correlate(mtcars, group = rep(c("A","B"), 16)) %>% as_matrix_data() %>% hyplot() + geom_square() ``` ``` -------------------------------- ### qcorrplot() — Quick correlation plot Source: https://context7.com/hy4m/linket/llms.txt Convenience wrapper around hyplot() for correlation objects. Adds geom_panel_grid(), sets coord_fixed(), and pre-maps fill, r, r0, and pvalue aesthetics automatically. Accepts correlate, rcorr, corr.test, or a raw matrix/data frame. ```APIDOC ## qcorrplot() ### Description Convenience wrapper around `hyplot()` for correlation objects. Adds `geom_panel_grid()`, sets `coord_fixed()`, and pre-maps `fill`, `r`, `r0`, and `pvalue` aesthetics automatically. Accepts `correlate`, `rcorr`, `corr.test`, or a raw matrix/data frame. ### Method `qcorrplot(data, type = "full", diag = TRUE, grid_col = "grey90", ...)` ### Parameters #### Arguments - **data**: Correlation object or matrix/data frame. - **type**: "full", "lower", or "upper" for the correlation matrix. - **diag**: Logical, whether to include the diagonal. - **grid_col**: Color of the grid lines. - **...**: Additional arguments passed to `hyplot()`. ### Request Example ```r library(ggplot2) # Full matrix with square markers qcorrplot(correlate(mtcars)) + geom_square() # Lower triangular, no diagonal, custom grid colour qcorrplot(correlate(mtcars), type = "lower", diag = FALSE, grid_col = "grey80") + geom_square() + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu")) # Upper triangular with significance marks qcorrplot(correlate(mtcars), type = "upper") + geom_square() + geom_mark() ``` ``` -------------------------------- ### mantel_test() — Mantel and partial-Mantel tests Source: https://context7.com/hy4m/linket/llms.txt Runs pairwise Mantel tests between species/community (spec) and environment (env) dissimilarity matrices. Supports column-subset grouping via spec_select / env_select, row-wise sample grouping via group, and partial Mantel via mantel_fun = "mantel.partial". ```APIDOC ## mantel_test() ### Description Runs pairwise Mantel tests between species/community (spec) and environment (env) dissimilarity matrices. Supports column-subset grouping via `spec_select` / `env_select`, row-wise sample grouping via `group`, and partial Mantel via `mantel_fun = "mantel.partial"`. ### Method `mantel_test(spec, env, ..., mantel_fun = "mantel", spec_select = NULL, env_select = NULL, group = NULL, env_ctrl = NULL)` ### Parameters #### Arguments - **spec**: Dissimilarity matrix for species/communities. - **env**: Dissimilarity matrix for environmental variables. - **mantel_fun**: Function to use for Mantel test (e.g., "mantel", "mantel.partial"). - **spec_select**: List for subsetting species columns. - **env_select**: List for subsetting environment columns. - **group**: Vector for grouping samples by rows. - **env_ctrl**: Control matrix for partial Mantel tests. ### Request Example ```r library(vegan) library(dplyr) data("varespec"); data("varechem") # Simple Mantel: each env variable vs spec groups mantel <- mantel_test( varespec, varechem, spec_select = list( Spec01 = 1:7, Spec02 = 8:18, Spec03 = 19:37, Spec04 = 38:44 ) ) %>% mutate( rd = cut(r, breaks = c(-Inf, 0.2, 0.4, Inf), labels = c("< 0.2", "0.2 - 0.4", ">= 0.4")), pd = cut(p, breaks = c(-Inf, 0.01, 0.05, Inf), labels = c("< 0.01", "0.01 - 0.05", ">= 0.05")) ) # Partial Mantel test ctrl <- matrix(rnorm(24 * 5), nrow = 24) mantel_partial <- mantel_test( varespec, varechem, env_ctrl = ctrl, mantel_fun = "mantel.partial" ) ``` ``` -------------------------------- ### Create Point Plot with hyplot and geom_point Source: https://github.com/hy4m/linket/blob/master/README.md Generates a point plot visualization using hyplot with geom_point. Useful for visualizing individual data points. ```r as_md_tbl(mtcars) %>% hyplot(aes(size = mtcars)) + geom_point(shape = 21, fill = NA) ``` -------------------------------- ### Custom Distance Function for Correlation Source: https://context7.com/hy4m/linket/llms.txt Demonstrates how to reorder correlation matrices using a custom distance function, such as Manhattan distance. ```r corr_sorted2 <- correlate(mtcars) %>% reorder_by(dist_fun = dist_func(.FUN = "dist", method = "manhattan")) ``` ```r # Reorder only rows, leave columns fixed corr_sorted3 <- correlate(mtcars) %>% reorder_by(by_cols = "none") ``` -------------------------------- ### regex_select(), prefix_with(), suffix_with(), contain_with() Source: https://context7.com/hy4m/linket/llms.txt Helper functions for subsetting data frames by column names using regular expressions or string patterns. ```APIDOC ## regex_select() / prefix_with() / suffix_with() / contain_with() ### Description Return data frames (or closure functions for use as `spec_select` / `env_select` entries) filtered by column-name patterns. Useful when passing subsets of a large data frame into `mantel_test()`. ### Method `regex_select(pattern, ...)` `prefix_with(x, prefix)` `suffix_with(x, suffix)` `contain_with(x, pattern)` ### Parameters - `pattern` (character): Regular expression pattern for `regex_select` and `contain_with`. - `prefix` (character): String to match at the beginning of column names for `prefix_with`. - `suffix` (character): String to match at the end of column names for `suffix_with`. - `x`: The input data frame. - `...`: Additional arguments for `regex_select`. ### Request Example ```r # Direct subsetting prefix_with(mtcars, "d") # columns starting with "d": disp, drat suffix_with(mtcars, "t") # columns ending with "t": drat, wt contain_with(mtcars, "a") # columns containing "a": drat, am, gear, carb # Inside mantel_test spec_select mantel_test( varespec, varechem, spec_select = list( grp1 = regex_select(prefix = "Cla"), grp2 = regex_select(suffix = "ma") ) ) ``` ``` -------------------------------- ### correlate() — Pairwise correlation matrices with p-values Source: https://context7.com/hy4m/linket/llms.txt Computes r-values and p-values for all column pairs of `x`, or between every column of `x` and `y`. Supports grouped analysis and multiple computation engines. ```APIDOC ## correlate() ### Description Computes r-values and p-values for all column pairs of `x`, or between every column of `x` and `y`. Supports grouped analysis and multiple computation engines. ### Usage ```r correlate(mtcars) correlate(mtcars, TRUE) # prints full list (r + p) correlate(m1, m2, method = "spearman") correlate(mtcars, group = grp) ``` ### Arguments - `x`: A matrix or data frame. - `y`: A matrix or data frame (optional). - `method`: Correlation method (e.g., "pearson", "spearman"). - `group`: A factor vector for grouped analysis. - `engine`: Computation engine (e.g., "psych"). ``` -------------------------------- ### theme_hy() Source: https://context7.com/hy4m/linket/llms.txt Applies a minimalist ggplot2 theme suitable for heatmaps, automatically applied by hyplot() and qcorrplot(). ```APIDOC ## theme_hy() ### Description Minimalist ggplot2 theme: removes axis titles and lines, sets black 10.5pt axis text, and rotates x-axis labels 90°. Applied automatically by `hyplot()` and `qcorrplot()`. ### Method `theme_hy(legend.position = "right", axis.text = element_text(size = 10.5, angle = 90, hjust = 1, vjust = 0.5, color = "black"), ...)` ### Parameters - `legend.position` (character): Position of the legend (e.g., "left", "right", "top", "bottom", "none"). - `axis.text` (ggplot2 element_text): Text style for axis labels. Defaults to black, 10.5pt, rotated. - `...`: Additional arguments to pass to `ggplot2::theme()`. ### Request Example ```r library(ggplot2) qcorrplot(correlate(mtcars)) + geom_square() + theme_hy(legend.position = "left", # override any theme param axis.text = element_text(size = 8)) ``` ``` -------------------------------- ### Link external data with geom_couple() Source: https://context7.com/hy4m/linket/llms.txt Connects external relationship data to heatmap rows using curved annotated lines. Requires 'from' and 'to' aesthetics. Use with mantel_test results. ```r library(vegan); library(dplyr) data("varespec"); data("varechem") mantel <- mantel_test( varespec, varechem, spec_select = list(Spec01 = 1:7, Spec02 = 8:18, Spec03 = 19:37, Spec04 = 38:44) ) %>% mutate( rd = cut(r, c(-Inf, 0.2, 0.4, Inf), c("< 0.2","0.2-0.4",">= 0.4")), pd = cut(p, c(-Inf, 0.01, 0.05, Inf), c("< 0.01","0.01-0.05",">= 0.05')) ) qcorrplot(correlate(varechem), type = "lower", diag = FALSE) + geom_square() + geom_couple( aes(colour = pd, size = rd), data = mantel, curvature = nice_curvature() ) + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu")) + scale_size_manual(values = c(0.5, 1, 2)) + scale_colour_manual(values = color_pal(3)) + guides( size = guide_legend(title = "Mantel's r"), colour = guide_legend(title = "Mantel's p"), fill = guide_colorbar(title = "Pearson's r") ) ``` -------------------------------- ### color_pal() / colour_pal() Source: https://context7.com/hy4m/linket/llms.txt Generates a qualitative color palette suitable for encoding p-value or r-value categories on geom_couple(). ```APIDOC ## color_pal() / colour_pal() ### Description Returns up to 6 qualitative colours (+ a grey for non-significant) suitable for encoding p-value or r-value categories on `geom_couple()`. ### Method `color_pal(n, alpha = 1)` ### Parameters - `n` (integer): The number of distinct colors to generate (up to 6). - `alpha` (numeric): The alpha transparency for the colors. ### Request Example ```r color_pal(3) # 3 colours: orange, teal, grey #> [1] "#D95F02" "#1B9E77" "#CCCCCC99" color_pal(4, alpha = 0.8) # Typical use inside geom_couple() scale_colour_manual(values = color_pal(3)) ``` ``` -------------------------------- ### Create Correlation Plot with qcorrplot and geom_square Source: https://github.com/hy4m/linket/blob/master/README.md Visualizes a correlation matrix using qcorrplot with geom_square. Supports custom color scales. ```r correlate(mtcars) %>% as_md_tbl() %>% qcorrplot() + geom_square() library(vegan) data("varespec") data("varechem") correlate(varespec[1:30], varechem) %>% qcorrplot() + geom_square() + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu")) ``` -------------------------------- ### matrix_data() — Create a multi-layer matrix container Source: https://context7.com/hy4m/linket/llms.txt Wraps one or more same-dimension matrices into a named list object that carries row/column names, display type, and diagonal settings. This is the fundamental data structure consumed by hyplot(). ```APIDOC ## matrix_data() ### Description Wraps one or more same-dimension matrices into a named list object that carries row/column names, display type, and diagonal settings. This is the fundamental data structure consumed by `hyplot()`. ### Usage ```r matrix_data(list(mtcars = mtcars)) matrix_data(list(r = r_mat, p = p_mat), type = "lower", diag = FALSE) ``` ### Arguments - `list`: A list of matrices. - `type`: Display type (e.g., "lower"). - `diag`: Whether to include the diagonal. ``` -------------------------------- ### Create Pairs Plot of Iris Dataset in R Source: https://github.com/hy4m/linket/blob/master/README.md This snippet shows how to generate a pairs plot for the iris dataset using the qpairs function from the linkET package. It includes a warning about a deprecated function. ```r qpairs(iris) + geom_pairs() #> Warning: 'use_md' has been deprecated, #> please set 'parse' parameter instead. ``` -------------------------------- ### Sort matrix rows/columns with reorder_by() Source: https://context7.com/hy4m/linket/llms.txt Sorts matrix rows or columns using hierarchical clustering by default. Accepts 'none' or clustering objects. Useful for reordering before plotting. ```r # Reorder correlation matrix via hclust then plot correlate(mtcars) %>% reorder_by() %>% qcorrplot() + geom_square() ``` ```r # Use a specific distance measure library(linkET) correlate(mtcars) %>% reorder_by(dist_fun = dist_func(.FUN = "dist", method = "euclidean"), by_cols = "none") %>% qcorrplot(type = "lower") + geom_square() ``` -------------------------------- ### Annotate correlations with geom_corr() Source: https://context7.com/hy4m/linket/llms.txt Adds formatted correlation coefficients and significance marks to facets in qpairs() plots. Use 'lc' position for lower-left corner. ```r library(ggplot2) qpairs(iris) + geom_pairs() + geom_corr(position = "lc", method = "pearson", digits = 2) ``` -------------------------------- ### Set global correlation plot style with set_corrplot_style() Source: https://context7.com/hy4m/linket/llms.txt Sets a session-wide fill scale for qcorrplot plots. Can use classic palettes, custom colours, or arbitrary ggplot2 scales. Revert with set_default_style(). ```r # Classic red-blue corrplot palette set_corrplot_style() qcorrplot(correlate(mtcars)) + geom_square() ``` ```r # Custom green-white-red set_corrplot_style(colours = c("green4", "white", "red3")) qcorrplot(correlate(mtcars)) + geom_square() ``` ```r # Arbitrary ggplot2 scale set_corrplot_style( scale = ggplot2::scale_fill_viridis_c(limits = c(-1, 1)) ) qcorrplot(correlate(mtcars)) + geom_square() ``` ```r # Revert to default (no fill scale) set_default_style() ``` -------------------------------- ### Process Matrix Data with matrix_data Source: https://github.com/hy4m/linket/blob/master/README.md Converts input data into a matrix data object suitable for linkET visualizations. Use as_matrix_data for direct conversion. ```r library(linkET) ## matrix_data matrix_data(list(mtcars = mtcars)) ## matrix_data matrix_data(list(mtcars = mtcars)) %>% as_md_tbl() ## as method as_matrix_data(mtcars) as_md_tbl(mtcars) ``` -------------------------------- ### Compute Relative Importance with calc_relimp Source: https://context7.com/hy4m/linket/llms.txt Computes the relative importance of environmental variables for explaining species variables using linear models. Requires the 'relaimpo' package. Returns explained variance (R²) and importance scores with p-values. ```r # Requires relaimpo package spec <- mtcars[c(1, 3, 4, 5)] # response variables env <- mtcars[6:11] # predictor variables result <- calc_relimp(spec, env, type = "lmg") print(result) #> ``` ```r # Visualise as a heatmap result$importance %>% as_matrix_data(name = "importance") %>% hyplot() + geom_tile(aes(fill = importance)) + scale_fill_gradientn(colours = color_pal(5)) ``` -------------------------------- ### Subsetting columns with regex_select() and helpers Source: https://context7.com/hy4m/linket/llms.txt Filters data frames by column name patterns for use in functions like mantel_test. Supports direct subsetting or closure functions for spec_select. ```r # Direct subsetting prefix_with(mtcars, "d") # columns starting with "d": disp, drat suffix_with(mtcars, "t") # columns ending with "t": drat, wt contain_with(mtcars, "a") # columns containing "a": drat, am, gear, carb ``` ```r # Inside mantel_test spec_select mantel_test( varespec, varechem, spec_select = list( grp1 = regex_select(prefix = "Cla"), grp2 = regex_select(suffix = "ma") ) ) ``` -------------------------------- ### Compute pairwise correlation matrices Source: https://context7.com/hy4m/linket/llms.txt Use `correlate()` to compute r-values and p-values for all column pairs. Supports grouped analysis and multiple computation engines. The `print()` function can display the r-matrix or the full list including p-values. ```r library(linkET) # All pairwise correlations in mtcars (Pearson, default) corr <- correlate(mtcars) print(corr) # prints r matrix print(corr, TRUE) # prints full list (r + p) # Cross-correlation: m1 columns vs m2 columns m1 <- matrix(rnorm(100), nrow = 10) m2 <- matrix(rnorm(60), nrow = 10) cross <- correlate(m1, m2, method = "spearman") # Grouped correlation (by a factor vector) grp <- rep(c("group1","group2"), each = 16) gc <- correlate(mtcars, group = grp) print(gc) #> Group: group1 #> A 11 rows, and 11 columns correlate object. #> Group: group2 #> A 11 rows, and 11 columns correlate object. # Using psych engine for richer output # correlate(mtcars, engine = "psych") ``` -------------------------------- ### geom_couple() Source: https://context7.com/hy4m/linket/llms.txt Connects external relationship data to heatmap rows using curved annotated lines. Requires 'from' and 'to' aesthetics. ```APIDOC ## geom_couple() ### Description Connects external relationship data (e.g., Mantel test results) to the rows of a `hyplot` / `qcorrplot` using curved annotated lines. Requires aesthetics `from` (group label in external data) and `to` (row name in the heatmap). ### Method `geom_couple(aes(colour = pd, size = rd), data = mantel, curvature = nice_curvature())` ### Parameters - `aes(colour = pd, size = rd)`: Aesthetics mapping for color and size. - `data`: The data frame containing the relationship data (e.g., mantel test results). - `curvature`: A function to determine the curvature of the lines. ### Request Example ```r library(vegan); library(dplyr) data("varespec"); data("varechem") mantel <- mantel_test( varespec, varechem, spec_select = list(Spec01 = 1:7, Spec02 = 8:18, Spec03 = 19:37, Spec04 = 38:44) ) %>% mutate( rd = cut(r, c(-Inf, 0.2, 0.4, Inf), c("< 0.2","0.2-0.4",">= 0.4")), pd = cut(p, c(-Inf, 0.01, 0.05, Inf), c("< 0.01","0.01-0.05",">= 0.05")) ) qcorrplot(correlate(varechem), type = "lower", diag = FALSE) + geom_square() + geom_couple( aes(colour = pd, size = rd), data = mantel, curvature = nice_curvature() ) + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu")) + scale_size_manual(values = c(0.5, 1, 2)) + scale_colour_manual(values = color_pal(3)) + guides( size = guide_legend(title = "Mantel's r"), colour = guide_legend(title = "Mantel's p"), fill = guide_colorbar(title = "Pearson's r") ) ``` ``` -------------------------------- ### as_matrix_data() — Coerce objects to matrix_data Source: https://context7.com/hy4m/linket/llms.txt Converts matrices, data frames, `correlate`, `rcorr`, or `corr.test` objects directly into a `matrix_data`. The `include` argument restricts data frames to numeric, character, or factor columns. ```APIDOC ## as_matrix_data() ### Description Converts matrices, data frames, `correlate`, `rcorr`, or `corr.test` objects directly into a `matrix_data`. The `include` argument restricts data frames to numeric, character, or factor columns. ### Usage ```r as_matrix_data(mtcars, name = "cars") as_matrix_data(corr_obj) ``` ### Arguments - `obj`: Object to convert. - `name`: Name for the matrix data. - `include`: Columns to include from data frames. ``` -------------------------------- ### reorder_by() Source: https://context7.com/hy4m/linket/llms.txt Sorts matrix rows or columns using hierarchical clustering or other specified methods. ```APIDOC ## reorder_by() ### Description Sorts matrix rows/columns. Available for `matrix`, `data.frame`, `correlate`, `matrix_data`, and `md_tbl`. By default uses hierarchical clustering; accepts `"none"` to leave an axis unchanged, or any `hclust` / `dist` / `dendrogram` / ggtree object. ### Method `reorder_by(x, by_rows = TRUE, by_cols = TRUE, dist_fun = NULL, hclust_fun = NULL)` ### Parameters - `x`: The input data (matrix, data.frame, etc.). - `by_rows` (logical or character): Whether to reorder rows. Can be `TRUE` (default hierarchical clustering), `"none"`, or a clustering object. - `by_cols` (logical or character): Whether to reorder columns. Can be `TRUE` (default hierarchical clustering), `"none"`, or a clustering object. - `dist_fun` (function, optional): A function to compute distances (e.g., `dist()`). - `hclust_fun` (function, optional): A function to perform hierarchical clustering (e.g., `hclust()`). ### Request Example ```r # Reorder correlation matrix via hclust then plot correlate(mtcars) %>% reorder_by() %>% qcorrplot() + geom_square() # Use a specific distance measure library(linkET) correlate(mtcars) %>% reorder_by(dist_fun = dist_func(.FUN = "dist", method = "euclidean"), by_cols = "none") %>% qcorrplot(type = "lower") + geom_square() ``` ``` -------------------------------- ### Visualize Lower Triangle of Correlation Matrix Source: https://github.com/hy4m/linket/blob/master/README.md Displays only the lower triangle of a correlation matrix using qcorrplot. Requires custom color scales. ```r qcorrplot(varespec[1:30], type = "lower") + geom_square() + scale_fill_gradientn(colours = RColorBrewer::brewer.pal(11, "RdBu")) ``` -------------------------------- ### set_corrplot_style() / set_default_style() Source: https://context7.com/hy4m/linket/llms.txt Sets a global color scale for qcorrplot plots, mimicking classic palettes or user-defined scales. ```APIDOC ## set_corrplot_style() / set_default_style() ### Description Sets a session-wide `scale_fill_gradientn` for `qcorrplot` plots, mimicking the classic corrplot red-blue palette or any user-supplied colours/scale. ### Method `set_corrplot_style(colours = NULL, scale = NULL)` `set_default_style()` ### Parameters - `colours` (character vector, optional): A vector of colors to use for the gradient scale. - `scale` (ggplot2 scale function, optional): A custom ggplot2 fill scale function. ### Request Example ```r # Classic red-blue corrplot palette set_corrplot_style() qcorrplot(correlate(mtcars)) + geom_square() # Custom green-white-red set_corrplot_style(colours = c("green4", "white", "red3")) qcorrplot(correlate(mtcars)) + geom_square() # Arbitrary ggplot2 scale set_corrplot_style( scale = ggplot2::scale_fill_viridis_c(limits = c(-1, 1)) ) qcorrplot(correlate(mtcars)) + geom_square() # Revert to default (no fill scale) set_default_style() ``` ``` -------------------------------- ### Draw Custom Shapes with geom_shaping() Source: https://context7.com/hy4m/linket/llms.txt Draws arbitrary marker shapes (circle, ellipse, etc.) in correlation cells, controlled by the 'marker' aesthetic or parameter. Useful for encoding additional information. ```r set_corrplot_style() # apply corrplot-style red-blue colour scale # Circle markers qcorrplot(correlate(mtcars)) + geom_shaping(marker = marker("circle")) ``` ```r # Ellipse whose angle encodes sign; shade layer for direction qcorrplot(correlate(mtcars), type = "lower") + geom_shaping(aes(r0 = abs(r)), marker = marker("ellipse")) + geom_shaping( aes(angle = ifelse(r > 0, 0, 180)), marker = marker("shade"), colour = "white", size = 0.3 ) set_default_style() # reset ``` -------------------------------- ### Apply Custom Styles to Correlation Plots Source: https://github.com/hy4m/linket/blob/master/README.md Allows setting custom styles for correlation plots using set_corrplot_style(). Resets to default with set_default_style(). ```r ## you can set your style set_corrplot_style() qcorrplot(mtcars) + geom_square() ## reset to default style set_default_style() ``` -------------------------------- ### Apply minimalist theme with theme_hy() Source: https://context7.com/hy4m/linket/llms.txt Applies a minimalist ggplot2 theme suitable for heatmaps, removing axis titles and lines. Can override theme parameters. ```r library(ggplot2) qcorrplot(correlate(mtcars)) + geom_square() + theme_hy(legend.position = "left", # override any theme param axis.text = element_text(size = 8)) ``` -------------------------------- ### Auto-compute curve direction with nice_curvature() Source: https://context7.com/hy4m/linket/llms.txt Automatically assigns curvature to linking edges in geom_couple() to prevent overlap. Can be configured by target row or source group position. ```r # Default (curvature = 0.1, determine by target row position) nice_curvature() ``` ```r # Higher curvature, determine by source group position nice_curvature(curvature = 0.25, by = "from") ``` -------------------------------- ### Create matrix_data object Source: https://context7.com/hy4m/linket/llms.txt Use `matrix_data()` to wrap one or more matrices into a named list object. This is the fundamental data structure consumed by `hyplot()`. It supports specifying display type and diagonal settings. ```r library(linkET) # Single matrix md <- matrix_data(list(mtcars = mtcars)) print(md) #> A matrix data object: #> Number: 1 #> Names: mtcars #> Dimensions: 32 rows, 11 columns # Two matrices with triangular display (requires square, symmetric data) r_mat <- cor(mtcars) p_mat <- matrix(runif(121), nrow = 11, dimnames = dimnames(r_mat)) md2 <- matrix_data(list(r = r_mat, p = p_mat), type = "lower", diag = FALSE) print(md2) ``` -------------------------------- ### Reorder matrix by hierarchical clustering Source: https://context7.com/hy4m/linket/llms.txt Use `reorder_by()` to reorder rows and columns of a matrix, `correlate`, or `matrix_data` object. Supports reordering by hierarchical clustering, dendrogram, `dist` object, or an explicit index vector. Attaches tree attributes for dendrogram display. ```r # Default hclust reorder of a correlate object corr_sorted <- correlate(mtcars) %>% reorder_by() ``` -------------------------------- ### Process Correlation Matrix Data Source: https://github.com/hy4m/linket/blob/master/README.md Calculates the correlation matrix for input data and converts it into a matrix data object or a tibble for visualization. ```r correlate(mtcars) %>% as_matrix_data() correlate(mtcars) %>% as_md_tbl() ``` -------------------------------- ### Coerce objects to matrix_data Source: https://context7.com/hy4m/linket/llms.txt Use `as_matrix_data()` to convert matrices, data frames, or correlation objects into a `matrix_data` object. For data frames, the `include` argument can restrict columns to specific types. ```r # From a plain data frame (numeric columns selected automatically) md <- as_matrix_data(mtcars, name = "cars") # From a correlate object (adds 'cor_matrix_data' sub-class) corr_obj <- correlate(mtcars) md_corr <- as_matrix_data(corr_obj) print(md_corr) #> A matrix data object: #> Number: 2 #> Names: r, p #> Dimensions: 11 rows, 11 columns ``` -------------------------------- ### Mantel Test for Species and Environment Data Source: https://context7.com/hy4m/linket/llms.txt Performs Mantel and partial Mantel tests to assess the relationship between species composition and environmental variables. Requires 'vegan' and 'dplyr' packages. ```r library(vegan) library(dplyr) data("varespec"); data("varechem") # Simple Mantel: each env variable vs spec groups mantel <- mantel_test( varespec, varechem, spec_select = list( Spec01 = 1:7, Spec02 = 8:18, Spec03 = 19:37, Spec04 = 38:44 ) ) %>% mutate( rd = cut(r, breaks = c(-Inf, 0.2, 0.4, Inf), labels = c("< 0.2", "0.2 - 0.4", ">= 0.4")), pd = cut(p, breaks = c(-Inf, 0.01, 0.05, Inf), labels = c("< 0.01", "0.01 - 0.05", ">= 0.05")) ) ``` ```r # Partial Mantel test ctrl <- matrix(rnorm(24 * 5), nrow = 24) mantel_partial <- mantel_test( varespec, varechem, env_ctrl = ctrl, mantel_fun = "mantel.partial" ) ``` -------------------------------- ### nice_curvature() Source: https://context7.com/hy4m/linket/llms.txt Automatically computes curve direction for linking edges in geom_couple() to prevent overlap. ```APIDOC ## nice_curvature() ### Description Returns a function that automatically assigns positive or negative curvature to each linking edge in `geom_couple()` so curves do not overlap. ### Method `nice_curvature(curvature = 0.1, by = "target")` ### Parameters - `curvature` (numeric): Controls the degree of curvature. Defaults to 0.1. - `by` (character): Specifies how to determine curvature. Can be "target" (default, based on target row position) or "from" (based on source group position). ### Request Example ```r # Default (curvature = 0.1, determine by target row position) nice_curvature() # Higher curvature, determine by source group position nice_curvature(curvature = 0.25, by = "from") ``` ``` -------------------------------- ### geom_mark() — Significance labels Source: https://context7.com/hy4m/linket/llms.txt Overlays formatted correlation coefficients and/or star significance marks (*, **, ***) on each cell. The pvalue aesthetic is required; r is optional for showing numeric values alongside stars. ```APIDOC ## geom_mark() ### Description Overlays formatted correlation coefficients and/or star significance marks (*, **, ***) on each cell. The `pvalue` aesthetic is required; `r` is optional for showing numeric values alongside stars. ### Method `geom_mark(mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., only_mark = TRUE, sig_level = c(0.05, 0.01, 0.001), mark = c("*", "**", "***"), sig_thres = 0.05, sep = " ", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)` ### Parameters #### Aesthetics - **pvalue**: Required aesthetic for significance level. - **r**: Optional aesthetic for correlation coefficient value. #### Arguments - **only_mark**: If TRUE, only shows significance marks; if FALSE, shows coefficient and marks. - **sig_level**: Significance levels for marks. - **mark**: Significance marks (e.g., "*", "**", "***"). - **sig_thres**: Threshold for significance. - **sep**: Separator between coefficient and marks. ### Request Example ```r qcorrplot(correlate(mtcars)) + geom_square() + geom_mark( only_mark = FALSE, # show number + stars sig_level = c(0.05, 0.01, 0.001), mark = c("*", "**", "***"), sig_thres = 0.05, # only label cells with p ≤ 0.05 sep = "\n" ) ``` ``` -------------------------------- ### geom_shaping() — Custom-shape correlation cells Source: https://context7.com/hy4m/linket/llms.txt Draws arbitrary marker shapes (circle, ellipse, heart, star, shade, etc.) at each cell position. Shape is controlled via the marker aesthetic or the marker parameter (a marker() object). ```APIDOC ## geom_shaping() ### Description Draws arbitrary marker shapes (circle, ellipse, heart, star, shade, etc.) at each cell position. Shape is controlled via the `marker` aesthetic or the `marker` parameter (a `marker()` object). ### Method `geom_shaping(mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., marker = NULL, colour = "black", size = 1, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)` ### Parameters #### Aesthetics - **marker**: Aesthetic for specifying the shape of the marker. - **r0**: Aesthetic for sizing the marker. - **angle**: Aesthetic for controlling the angle of the marker (e.g., for ellipses). #### Arguments - **marker**: A `marker()` object specifying the shape. - **colour**: Color of the marker. - **size**: Size of the marker. ### Request Example ```r set_corrplot_style() # apply corrplot-style red-blue colour scale # Circle markers qcorrplot(correlate(mtcars)) + geom_shaping(marker = marker("circle")) # Ellipse whose angle encodes sign; shade layer for direction qcorrplot(correlate(mtcars), type = "lower") + geom_shaping(aes(r0 = abs(r)), marker = marker("ellipse")) + geom_shaping( aes(angle = ifelse(r > 0, 0, 180)), marker = marker("shade"), colour = "white", size = 0.3 ) set_default_style() # reset ``` ``` -------------------------------- ### reorder_by() — Hierarchical-clustering reorder Source: https://context7.com/hy4m/linket/llms.txt Reorders rows and columns of a matrix, `correlate`, or `matrix_data` object using hierarchical clustering, a dendrogram, a `dist` object, or an explicit index vector. Attaches tree attributes used by `hyplot()` for dendrogram display. ```APIDOC ## reorder_by() ### Description Reorders rows and columns of a matrix, `correlate`, or `matrix_data` object using hierarchical clustering, a dendrogram, a `dist` object, or an explicit index vector. Attaches tree attributes used by `hyplot()` for dendrogram display. ### Usage ```r correlate(mtcars) %>% reorder_by() ``` ### Arguments - `obj`: A matrix, `correlate`, or `matrix_data` object. - `method`: Reordering method (e.g., hierarchical clustering). ``` -------------------------------- ### Add Significance Labels with geom_mark() Source: https://context7.com/hy4m/linket/llms.txt Overlays correlation coefficients and/or significance stars on correlation plot cells. Requires the 'pvalue' aesthetic and optionally 'r'. ```r qcorrplot(correlate(mtcars)) + geom_square() + geom_mark( only_mark = FALSE, # show number + stars sig_level = c(0.05, 0.01, 0.001), mark = c("*", "**", "***"), sig_thres = 0.05, # only label cells with p ≤ 0.05 sep = "\n" ) ``` -------------------------------- ### geom_corr() Source: https://context7.com/hy4m/linket/llms.txt Adds formatted correlation coefficients with optional significance marks to pairs plots. ```APIDOC ## geom_corr() ### Description Adds a formatted correlation coefficient annotation (with optional significance mark) to each facet panel in a pairs plot created by `qpairs()`. ### Method `geom_corr(position = "lc", method = "pearson", digits = 2)` ### Parameters - `position` (character): Specifies the position of the annotation (e.g., "lc" for lower-left). - `method` (character): The correlation method to use (e.g., "pearson"). - `digits` (integer): The number of digits to display for the correlation coefficient. ### Request Example ```r library(ggplot2) qpairs(iris) + geom_pairs() + geom_corr(position = "lc", method = "pearson", digits = 2) ``` ``` -------------------------------- ### Adjust p-values for multiple testing Source: https://context7.com/hy4m/linket/llms.txt Use `adjust_pvalue()` to adjust p-values within a `correlate` or `cor_md_tbl` object. Supports methods from `stats::p.adjust` and multtest procedures. ```r corr <- correlate(mtcars) %>% adjust_pvalue(method = "BH") # Benjamini-Hochberg # Or Bonferroni corr_bonf <- correlate(mtcars) %>% adjust_pvalue(method = "bonferroni") ```