| Title: | High-Level Plotting Built Upon 'ggplot2' and Other Plotting Packages |
| Version: | 0.13.1 |
| Description: | Provides high-level API and a wide range of options to create stunning, publication-quality plots effortlessly. It is built upon 'ggplot2' and other plotting packages, and is designed to be easy to use and to work seamlessly with 'ggplot2' objects. It is particularly useful for creating complex plots with multiple layers, facets, and annotations. It also provides a set of functions to create plots for specific types of data, such as Venn diagrams, alluvial diagrams, and phylogenetic trees. The package is designed to be flexible and customizable, and to work well with the 'ggplot2' ecosystem. The API can be found at https://pwwang.github.io/plotthis/reference/index.html. |
| License: | GPL (≥ 3) |
| Encoding: | UTF-8 |
| URL: | https://github.com/pwwang/plotthis https://pwwang.github.io/plotthis/ |
| BugReports: | https://github.com/pwwang/plotthis/issues |
| RoxygenNote: | 7.3.3 |
| Depends: | R (≥ 4.2.0) |
| Imports: | circlize, ggplot2, rlang, dplyr, tidyr, glue, forcats, gtable, reshape2, stringr, scales, gridtext, methods, patchwork, ggrepel, ggnewscale, cowplot, zoo |
| Suggests: | plotly, testthat, Matrix, alluvial, datasets, ComplexHeatmap, cluster, clustree, gglogger, ggwordcloud, ggalluvial, ggVennDiagram (≥ 1.5.0), ggupset, ggpubr, ggbeeswarm, ggforce, ggraph, ggridges, ggmanh, qqplotr, hexbin, igraph, iNEXT, scattermore, sf, terra, concaveman, plotROC, OptimalCutpoints, proxyC, metR |
| LazyData: | true |
| Additional_repositories: | https://bioconductor.org/packages/release/bioc |
| Config/Needs/website: | rmarkdown |
| NeedsCompilation: | no |
| Packaged: | 2026-07-09 06:20:10 UTC; pwwang |
| Author: | Panwen Wang |
| Maintainer: | Panwen Wang <pwwang@pwwang.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-07-09 11:00:02 UTC |
Heatmap annotation function for categorical data
Description
Heatmap annotation function for categorical data
Usage
.anno_ggcat(
x,
split_by = NULL,
group_by,
column,
title,
side = "left",
which = "row",
palette,
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
.plotting,
...
)
Arguments
x |
A data frame |
split_by |
A character string of the column name to split the data |
group_by |
A character string of the column name to group the data |
column |
A character string of the column name to plot |
title |
A character string to name the legend |
side |
A character string showing where the annotation is. |
which |
A character string specifying the direction of the annotation. Default is "row". Other options are "column". |
palette |
A character string specifying the palette of the annotation |
palcolor |
A character vector of colors to override the palette |
border |
A logical value indicating whether to draw the border of the annotation |
legend.direction |
A character string specifying the direction of the legend. Default is "vertical". Other options are "horizontal". |
show_legend |
A logical value indicating whether to show the legend |
.plotting |
A function to create the plot for each split and each group |
... |
Other arguments passed to |
Heatmap annotation functions
Description
Heatmap annotation functions
Usage
.anno_ggseries(
x,
split_by = NULL,
group_by,
column,
title,
side = "left",
which = "row",
palette,
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
.plotting,
...
)
anno_pie(
x,
split_by = NULL,
group_by,
column,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
...
)
anno_ring(
x,
split_by = NULL,
group_by,
column,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
...
)
anno_bar(
x,
split_by = NULL,
group_by,
column,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
...
)
anno_violin(
x,
split_by = NULL,
group_by,
column,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
...
)
anno_boxplot(
x,
split_by = NULL,
group_by,
column,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
...
)
anno_density(
x,
split_by = NULL,
group_by,
column,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
...
)
anno_simple(
x,
split_by = NULL,
group_by = NULL,
column = NULL,
title,
which = "row",
side = "left",
palette,
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
alpha = 1,
...
)
anno_points(
x,
split_by = NULL,
group_by,
column,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
alpha = 1,
...
)
anno_lines(
x,
split_by = NULL,
group_by,
column,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = TRUE,
alpha = 1,
add_points = TRUE,
...
)
anno_block(
x,
split_by = NULL,
group_by = NULL,
column = NULL,
title,
which = "row",
side = "left",
palette,
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = FALSE,
alpha = 1,
...
)
anno_text(
x,
split_by = NULL,
group_by,
column = NULL,
title,
which = "row",
palette,
side = "left",
palcolor = NULL,
border = TRUE,
legend.direction,
show_legend = FALSE,
alpha = 1,
...
)
Arguments
x |
A data frame |
split_by |
A character string of the column name to split the data (heatmap) |
group_by |
A character string of the column name to group the data (rows or columns of the heatmap) |
column |
A character string of the column name of the data |
title |
A character string to name the legend |
side |
A character string specifying the side of the annotation. Default is "left". |
which |
A character string specifying the direction of the annotation. Default is "row". Other options are "column". |
palette |
A character string specifying the palette of the annotation |
palcolor |
A character vector of colors to override the palette |
border |
A logical value indicating whether to draw the border of the annotation |
legend.direction |
A character string specifying the direction of the legend. Default is "vertical". Other options are "horizontal". |
show_legend |
A logical value indicating whether to show the legend |
.plotting |
A function to create the plot for each split and each group |
... |
Other arguments passed to |
alpha |
A numeric value between 0 and 1 specifying the transparency of the annotation |
add_points |
A logical value indicating whether to add points to the annotation |
Apply ordering to a data frame based on a specified expression
Description
Apply ordering to a data frame based on a specified expression
Usage
.apply_orderby(df, orderby, by, sby, sby_levels)
Arguments
df |
A data frame to be ordered. |
orderby |
A character string representing the expression to order by. |
by |
A character string representing the column name to group by. |
sby |
A character string representing the column name to group by for secondary ordering. |
sby_levels |
A character vector representing the levels of the secondary grouping column. |
Value
A data frame ordered based on the specified expression.
Check the annotation specification The annotations should not be any of by or split_by, and the columns must exist in the data
Description
Check the annotation specification The annotations should not be any of by or split_by, and the columns must exist in the data
Usage
.check_annotation(data, annotation, by, split_by, which)
Arguments
data |
The data for Heatmap plot |
annotation |
The annotation mappings |
by |
The column for rows or columns |
split_by |
The column for row or column splitting |
which |
If the annotation is for row or column |
Compute velocity on a regular grid from sparse cell embeddings
Description
Computes velocity vectors on a regular grid by averaging cell-level velocities within a Gaussian-weighted neighborhood of each grid point. This function is adapted from the scvelo Python implementation at https://github.com/theislab/scvelo/blob/master/scvelo/plotting/velocity_embedding_grid.py.
Usage
.compute_velocity_on_grid(
embedding,
v_embedding,
density = NULL,
smooth = NULL,
n_neighbors = NULL,
min_mass = NULL,
scale = 1,
adjust_for_stream = FALSE,
cutoff_perc = NULL
)
Arguments
embedding |
A numeric matrix of dimension n_obs x n_dim containing the low-dimensional embedding coordinates of each cell. |
v_embedding |
A numeric matrix of dimension n_obs x n_dim containing the velocity vectors for each cell. |
density |
A numeric value specifying the density of the grid points along each dimension. Higher values produce a finer grid. Default is 1. |
smooth |
A numeric value specifying the standard deviation multiplier for the Gaussian kernel used to weight neighboring cells when averaging velocities onto grid points. Default is 0.5. |
n_neighbors |
An integer value specifying the number of nearest neighbors to consider for each grid point when computing the weighted average velocity. Default is |
min_mass |
A numeric value specifying the minimum mass threshold. Grid points with total weight below this threshold are filtered out. When |
scale |
A numeric value specifying the scaling factor to apply to the resulting grid velocity vectors. Only used when |
adjust_for_stream |
A logical value indicating whether to adjust the output for streamline rendering. When |
cutoff_perc |
A numeric value specifying the percentile cutoff for removing low-density grid points. Only used when |
Value
A list with components x_grid (grid point coordinates) and v_grid (velocity vectors at each grid point). When adjust_for_stream = TRUE, x_grid is a 2-row matrix of unique coordinates and v_grid is a 3D array.
Flip y-coordinates for spatial data objects
Description
These internal S3 methods flip the y-coordinates of SpatRaster,
SpatVector, and data.frame objects.
For rasters, the raster is flipped vertically and its extent is negated. For vectors, the y-coordinates of all geometries are negated. For data frames, the specified y column is negated.
Usage
.flip_y(data, ...)
## S3 method for class 'SpatRaster'
.flip_y(data, ...)
## S3 method for class 'SpatVector'
.flip_y(data, ...)
## S3 method for class 'data.frame'
.flip_y(data, y = "y", ...)
Arguments
data |
A |
... |
Additional arguments (not used). |
y |
A character string specifying the y column name for |
Details
These functions are intended for internal use to facilitate coordinate
transformations. When visualizing spatial data, it is often necessary to
flip the y-axis to put the origin at the top-left corner. However,
geom_sf() does not work with
scale_y_reverse(). See
this
GitHub comment for details. These functions negate the y-coordinates so
that the axis labels can be displayed with reversed sign, mimicking
scale_y_reverse().
Value
For SpatRaster input, a SpatRaster flipped vertically with
negated y-extent. For SpatVector input, a SpatVector with
negated y-coordinates. For data.frame input, a data frame with the
specified y column negated.
Get the grid.draw-able ggplot grob The output from ggplotGrob can not be directly used in grid.draw, the position can not be set. This function extracts the gTree from the ggplot grob.
Description
Get the grid.draw-able ggplot grob The output from ggplotGrob can not be directly used in grid.draw, the position can not be set. This function extracts the gTree from the ggplot grob.
Usage
.gggrob(p, void = TRUE, nolegend = TRUE)
Arguments
p |
A ggplot object |
void |
If TRUE, the theme_void will be added to the ggplot object |
nolegend |
If TRUE, the legend will be removed from the ggplot object |
Value
A gTree object
Prepare and normalize annotation arguments
Description
Consolidates the new structured annotation list format with backward-compatible
deprecation support for old flat arguments. Handles TRUE/FALSE
shortcuts, .default inheritance (with recursive params merge),
alias resolution, and shortcut expansion.
Usage
.prep_annotations(
which = c("row", "column"),
annotation = NULL,
annotation_side = NULL,
annotation_palette = NULL,
annotation_palcolor = NULL,
annotation_type = NULL,
annotation_params = NULL,
annotation_agg = NULL,
row_key = NULL,
rsplit_key = NULL,
col_key = NULL,
csplit_key = NULL,
data = NULL
)
Arguments
which |
|
annotation |
The new structured annotation list. |
annotation_side |
Deprecated. Old side argument. |
annotation_palette |
Deprecated. Old palette argument. |
annotation_palcolor |
Deprecated. Old palcolor argument. |
annotation_type |
Deprecated. Old type argument. |
annotation_params |
Deprecated. Old params argument. |
annotation_agg |
Deprecated. Old agg argument. |
row_key |
The actual column name for |
rsplit_key |
The actual column name for |
col_key |
The actual column name for |
csplit_key |
The actual column name for |
data |
The data frame used for column validation. |
Value
A list with components annotation, annotation_type,
annotation_side, annotation_palette, annotation_palcolor,
annotation_agg, annotation_params, and enabled.
Prepare the extent for spatial plots
Description
Prepare the extent for spatial plots
Usage
.prepare_extent(ext)
Arguments
ext |
A numeric vector of length 4 specifying the extent as |
Value
A SpatExtent object if ext is a numeric vector, or the original SpatExtent if it is already one.
NULL is returned if ext is NULL.
Reorder annotation list so split annotation (split_by) is farthest from heatmap body and name annotation (by) is closest. User annotations stay in between. For all annotation sides, ComplexHeatmap renders first-element = farthest, last-element = closest to the heatmap body.
Description
Reorder annotation list so split annotation (split_by) is farthest from heatmap body and name annotation (by) is closest. User annotations stay in between. For all annotation sides, ComplexHeatmap renders first-element = farthest, last-element = closest to the heatmap body.
Usage
.reorder_anno_side(x, by, split_by, side)
Arguments
x |
A list of annotations |
by |
The name of the annotation used for row/column names |
split_by |
The name of the annotation used for splitting rows/columns |
side |
The annotation side ("top", "bottom", "left", "right") |
Value
A reordered list of annotations
Resolve annotation aliases: .row -> rows_by .rows.split -> rows_split_by .col/.column -> columns_by .col.split/.column.split -> columns_split_by
Description
Resolve annotation aliases: .row -> rows_by .rows.split -> rows_split_by .col/.column -> columns_by .col.split/.column.split -> columns_split_by
Usage
.resolve_anno_aliases(lst, row_key, rsplit_key, col_key, csplit_key)
Arguments
lst |
A list of annotations, which may contain aliases for rows_by, rows_split_by, columns_by, and columns_split_by. |
row_key |
The actual key for rows_by in the list. |
rsplit_key |
The actual key for rows_split_by in the list. |
col_key |
The actual key for columns_by in the list. |
csplit_key |
The actual key for columns_split_by in the list. |
Value
A list of annotations with aliases resolved to the actual keys.
Unified annotation builder for built-in (split/name) and user-defined annotations
Description
Unified annotation builder for built-in (split/name) and user-defined annotations
Usage
.setup_annos(
which,
names_side,
anno_title,
show_names,
annotation,
annotation_type,
annotation_side,
annotation_palette,
annotation_palcolor,
annotation_agg,
annotation_params,
split_by,
splits,
by,
by_labels,
flip,
legend.direction,
legend.position,
data
)
Arguments
which |
The annotation direction ("row" or "column") |
names_side |
The side to place the row/column name annotation ("top", "bottom", "left", "right") |
anno_title |
The title of the annotation (for split) |
show_names |
A logical value indicating whether to show row/column names |
annotation |
A list of user-defined annotations, where names are annotation names and values are annotation objects or parameters to build annotation objects |
annotation_type |
A list of annotation types, where names are annotation names and values are annotation types ("simple", "label", "block", "ggcat", "ggseries", or "auto") |
annotation_side |
A list of annotation sides, where names are annotation names and values are annotation sides ("top", "bottom", "left", "right") |
annotation_palette |
A list of annotation palettes, where names are annotation names and values are palette names or color vectors |
annotation_palcolor |
A list of annotation palette colors, where names are annotation names and values are color vectors to override the palette |
annotation_agg |
A list of functions to aggregate the original data for each annotation, where names are annotation names and values are functions that take a vector of values in the cell and return an aggregated value |
annotation_params |
A list of additional parameters for each annotation, where names are annotation names and values are lists of parameters to pass to the annotation constructor |
split_by |
The name of the column used for split annotation |
splits |
A factor vector of splits for the split annotation |
by |
The name of the column used for name annotation |
by_labels |
A factor vector of labels for the name annotation |
flip |
A logical value indicating whether to flip the annotation (for ggseries annotations) |
legend.direction |
The direction of the legend ("vertical" or "horizontal") |
legend.position |
The position of the legend ("right", "left", "top", "bottom") |
data |
A data frame used for ggcat and ggseries annotations, where each row corresponds to a cell in the heatmap and contains the original values before aggregation |
Value
A list of annotations and legends to be passed to ComplexHeatmap.
Wrap spatial plot if plotted independently
Description
This function is used to wrap spatial plots if they are plotted independently with return_layer = FALSE.
Usage
.wrap_spatial_layers(
layers,
ext = NULL,
flip_y = TRUE,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
theme = "theme_box",
theme_args = list()
)
Arguments
layers |
A list of ggplot layers to be wrapped. |
ext |
A numeric vector of length 4 specifying the extent as |
flip_y |
Whether to flip the y-axis direction. Default is TRUE. |
legend.position |
The position of the legend. Default is "right". |
legend.direction |
The direction of the legend. Default is "vertical". |
title |
The title of the plot. Default is NULL. |
subtitle |
The subtitle of the plot. Default is NULL. |
xlab |
The x-axis label. Default is NULL. |
ylab |
The y-axis label. Default is NULL. |
theme |
The theme to be used for the plot. Default is "theme_box". |
theme_args |
A list of arguments to be passed to the theme function. Default is an empty list. |
Value
A ggplot object with the specified layers.
Area plot
Description
Draws a stacked area plot showing how one or more groups' numeric values (or counts) accumulate across the progression of a discrete x-axis variable. Each group is rendered as a filled area stacked from baseline, making it easy to compare both individual magnitudes and the total across categories.
The function supports count aggregation (omit y to plot
observation counts per x-category), proportion scaling
(scale_y = TRUE normalises each x position to 100\
colour control, faceting, and splitting into separate sub-plots via
split_by.
Usage
AreaPlot(
data,
x,
y = NULL,
x_sep = "_",
split_by = NULL,
split_by_sep = "_",
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
scale_y = FALSE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
x_sep |
A character string used to join multiple |
split_by |
The column(s) to split the data by and produce separate
sub-plots. Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string used as the fill legend title.
When |
scale_y |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
seed |
A numeric seed for reproducibility. Passed to
|
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default |
axes |
A character string specifying how axes should be treated across
the combined layout (passed to |
axis_titles |
A character string specifying how axis titles should be
treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should be
collected across panels. Default |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments. |
Value
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by workflow
When split_by is provided:
-
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments for all columns (x,split_by,group_by,facet_by). The
split_bycolumn is validated and its NA / empty levels are processed viaprocess_keep_na_empty(). It is then removed from the per-columnkeep_na/keep_emptylists.The data frame is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
AreaPlotAtomic()is called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
set.seed(8525)
data <- data.frame(
x = rep(c("A", "B", "C", "D"), 2),
y = c(1, 3, 6, 4, 2, 5, 7, 8),
group = rep(c("F1", "F2"), each = 4),
split = rep(c("X", "Y"), 4)
)
# Basic stacked area
AreaPlot(data, x = "x", y = "y", group_by = "group")
# Scaled to proportions
AreaPlot(data, x = "x", y = "y", group_by = "group",
scale_y = TRUE)
# Split into sub-plots (no group_by — single-colour fill)
AreaPlot(data, x = "x", y = "y", split_by = "group")
# Per-split palettes
AreaPlot(data, x = "x", y = "y", split_by = "group",
palette = c(F1 = "Blues", F2 = "Reds"))
# Per-split legend positioning
AreaPlot(data, x = "x", y = "y", group_by = "group",
split_by = "split",
legend.direction = c(X = "horizontal", Y = "vertical"),
legend.position = c(X = "top", Y = "right"))
# How keep_na and keep_empty work
data <- data.frame(
x = factor(rep(c("A", NA, "C", "D"), 3),
levels = c("A", "B", "C", "D")),
y = c(1, 3, 6, 4, 2, 5, 7, 8, 4, 2, 3, 5),
group = factor(sample(rep(c("F1", NA, "F3"), each = 4)),
levels = c("F1", "F2", "F3")),
split = factor(sample(rep(c("X", "Y", NA), 4)),
levels = c("X", "Y", "Z")),
facet = factor(sample(rep(c("M", "N", NA), 4)),
levels = c("M", "N", "O"))
)
# Default: NA and empty levels dropped
AreaPlot(data, x = "x", y = "y", group_by = "group")
# Keep NA and empty levels
AreaPlot(data, x = "x", y = "y", group_by = "group",
keep_na = TRUE, keep_empty = TRUE)
# Keep NA, assign empty levels colours but don't show them
AreaPlot(data, x = "x", y = "y", group_by = "group",
keep_na = TRUE, keep_empty = "level")
# Drop NA, keep empty levels
AreaPlot(data, x = "x", y = "y", group_by = "group",
keep_na = FALSE, keep_empty = TRUE)
# Per-column keep_na / keep_empty via named lists
AreaPlot(data, x = "x", y = "y", group_by = "group",
keep_na = list(x = TRUE, group = FALSE),
keep_empty = list(x = FALSE, group = TRUE))
AreaPlot(data, x = "x", y = "y", group_by = "group",
keep_na = list(x = FALSE, group = TRUE),
keep_empty = list(x = TRUE, group = FALSE))
Atomic area plot (internal)
Description
Core implementation for drawing a single stacked area plot. This is the
workhorse behind the exported AreaPlot function — it takes a
single data frame (no split_by support) and returns a
ggplot object. The plot shows how one or more groups' numeric values
(or counts) accumulate across a discrete x-axis, with each group rendered
as a filled area stacked from baseline.
Usage
AreaPlotAtomic(
data,
x,
y = NULL,
x_sep = "_",
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
scale_y = FALSE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name to plot on the
x-axis. Must be character or factor. Multiple columns can be provided;
they are concatenated with |
y |
A character string specifying the numeric column for the y-axis.
When |
x_sep |
A character string used to join multiple |
group_by |
A character vector of column names to fill the areas by.
Each unique combination becomes a separate stacked area. Multiple
columns are concatenated with |
group_by_sep |
A character string to separate concatenated
|
group_name |
A character string used as the fill legend title.
When |
scale_y |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
Column resolution —
x,y,group_by, andfacet_byare validated and transformed viacheck_columns. Multi-column inputs forxandgroup_byare concatenated into single columns using their respective separators (x_sep,group_by_sep). -
NA / empty-level handling —
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. Per-columnkeep_emptysettings are extracted forx,group_by, andfacet_byindependently. The facet columns must have identicalkeep_emptyvalues. -
Count aggregation — when
y = NULL, the count of observations in each unique (x,group_by,facet_by) combination is computed as a new.countcolumn. Factor levels are preserved after aggregation. -
Proportion scaling — when
scale_y = TRUE, the y-values are divided by the sum within each (x,facet_by) group, producing a proportion (0–1). Percent labels are used automatically on the y-axis. -
Empty-fill guard — when
group_by = NULL(no grouping), a dummy.fillfactor is created so the single area still draws with the first palette colour. The legend is suppressed (legend.position = "none"). -
Colour mapping —
palette_this()assigns colours to allgroup_bylevels, includingNA(defaulting to"grey80"). -
Data completion —
complete()pads allx×group_by(×facet_by) combinations withy = 0. This preventsgeom_area()from interpolating across missing groups, which would otherwise cause stacked areas to exceed the correct total. -
x-axis numeric mapping — the discrete x variable is converted to a numeric position column (
.x_numeric) sogeom_area()can draw continuous area fills between x positions.NAlevels are placed at positionn_levels + 1. -
Plot assembly — the
ggplotobject is built withgeom_area(position = position_stack(vjust = 0.5)),scale_x_discrete()(breaks from factor levels),scale_y_continuous()(percent labels when scaled), andscale_fill_manual()with per-group colours. The fill scaledropargument is controlled bykeep_empty_group. -
Dimension calculation —
calculate_plot_dimensions()computes plot height and width from the x-axis category count,aspect.ratio, and legend metrics. The resultingheight/widthattributes are stored on theggplotobject. -
Faceting —
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided, respecting thekeep_emptysetting for facet variables.
Bar / SplitBar / Waterfall Plot
Description
BarPlot draws bar plots with flexible fill, grouping, labelling, and annotation
options. Supports both simple single-colour bars and grouped bars (dodged
or stacked). Bars can be filled by a categorical variable (discrete
colour scale), a continuous variable (colour gradient), or a fixed colour.
The function supports count aggregation (omit y to plot
observation counts), proportion scaling (scale_y = TRUE
for grouped bars), background stripes (add_bg), bar labels, trend
lines, horizontal reference lines, and splitting into separate sub-plots
via split_by.
SplitBarPlot (also known as WaterfallPlot) draws a divergent bar plot
where bars extend left (negative values) and right (positive values) from a
central zero line. The bar fill colour and opacity can encode additional
variables, and the vertical ordering of categories is fully customisable.
The function supports split_by to produce separate panels, facet_by for grouped views within panels, and alpha_by for encoding a secondary numeric variable via opacity.
Usage
BarPlot(
data,
x,
x_sep = "_",
y = NULL,
flip = FALSE,
fill_by = TRUE,
fill_name = NULL,
line_name = NULL,
label_nudge = 0.02,
label = NULL,
label_fg = "black",
label_size = 4,
label_bg = "white",
label_bg_r = 0.1,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
split_by = NULL,
split_by_sep = "_",
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
facet_args = list(),
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
add_trend = FALSE,
trend_color = "black",
trend_linewidth = 1,
trend_ptsize = 2,
theme = "theme_this",
theme_args = list(),
palette = NULL,
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
x_text_angle = 0,
aspect.ratio = 1,
y_min = NULL,
y_max = NULL,
position = "auto",
position_dodge_preserve = "total",
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_empty = FALSE,
keep_na = FALSE,
expand = waiver(),
width = waiver(),
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
SplitBarPlot(
data,
x,
y,
y_sep = "_",
flip = FALSE,
split_by = NULL,
split_by_sep = "_",
alpha_by = NULL,
alpha_reverse = FALSE,
alpha_name = NULL,
order_y = list(`+` = c("x_desc", "alpha_desc"), `-` = c("x_desc", "alpha_asc")),
bar_height = 0.9,
lineheight = 0.5,
max_charwidth = 80,
fill_by = NULL,
fill_by_sep = "_",
fill_name = NULL,
direction_name = "direction",
direction_pos_name = "positive",
direction_neg_name = "negative",
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
facet_by = NULL,
facet_scales = "free_y",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
x_min = NULL,
x_max = NULL,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_empty = FALSE,
keep_na = FALSE,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
WaterfallPlot(
data,
x,
y,
y_sep = "_",
flip = FALSE,
split_by = NULL,
split_by_sep = "_",
alpha_by = NULL,
alpha_reverse = FALSE,
alpha_name = NULL,
order_y = list(`+` = c("x_desc", "alpha_desc"), `-` = c("x_desc", "alpha_asc")),
bar_height = 0.9,
lineheight = 0.5,
max_charwidth = 80,
fill_by = NULL,
fill_by_sep = "_",
fill_name = NULL,
direction_name = "direction",
direction_pos_name = "positive",
direction_neg_name = "negative",
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
facet_by = NULL,
facet_scales = "free_y",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
x_min = NULL,
x_max = NULL,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_empty = FALSE,
keep_na = FALSE,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
x_sep |
A character string to join multiple |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
flip |
Logical; if |
fill_by |
A variable used to fill the bars. Both categorical and numeric columns are accepted:
Ignored when |
fill_name |
A character string for the fill legend title. Only
applies when |
line_name |
Legend name for the reference line. |
label_nudge |
A numeric value controlling the distance between labels and the bar top, expressed as a fraction of the data range. |
label |
A column name (or |
label_fg |
A character string specifying the label text colour. |
label_size |
A numeric value specifying the label text size. |
label_bg |
A character string specifying the label background colour. |
label_bg_r |
A numeric value specifying the label background corner radius. |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string for the group fill legend title.
When |
split_by |
The column(s) to split the data by for separate sub-plots. |
split_by_sep |
Separator for concatenated |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
facet_args |
A list of additional arguments passed to the faceting
function (e.g., |
add_bg |
Logical; add alternating background stripes behind the bars. |
bg_palette |
Palette for the background stripes. |
bg_palcolor |
Custom colours for the background stripes. |
bg_alpha |
Alpha transparency for the background stripes. |
add_line |
A numeric y-intercept for a horizontal reference line. |
line_color |
Colour of the reference line. |
line_width |
Width of the reference line. |
line_type |
Linetype of the reference line (e.g., 1 = solid, 2 = dashed). |
add_trend |
Logical; add a trend line and points connecting the bar tops. |
trend_color |
Colour of the trend line. |
trend_linewidth |
Width of the trend line. |
trend_ptsize |
Size of the trend line points. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
y_min, y_max |
Numeric limits for the y-axis (or x-axis when flipped). |
position |
A character string specifying the bar layout:
|
position_dodge_preserve |
A character string passed to
|
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
width |
A numeric value specifying the bar width (0–1). |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout. |
byrow |
Logical; fill the combined layout by row (default |
seed |
A numeric seed for reproducibility. |
axes, axis_titles |
Character strings for axis handling in the combined layout. |
guides |
Character string for legend collection across panels. |
design |
A custom layout design for the combined plot. |
... |
Additional arguments. |
y_sep |
A character string to join multiple |
alpha_by |
A character string naming a numeric column to encode as
bar opacity. Default |
alpha_reverse |
Logical; if |
alpha_name |
A character string for the alpha legend title. |
order_y |
A named list controlling the vertical ordering of bars.
Keys are |
bar_height |
A numeric value (0–1) specifying the bar height as a fraction of the available category slot. |
lineheight |
A numeric value controlling the line height of wrapped category labels. |
max_charwidth |
An integer specifying the maximum character width for wrapping category labels. |
fill_by_sep |
A character string to join multiple |
direction_name |
A character string naming the internal direction
column (used in legends). Default |
direction_pos_name |
A character string labelling the positive
direction in the legend. Default |
direction_neg_name |
A character string labelling the negative
direction in the legend. Default |
x_min, x_max |
Numeric limits for the x-axis. When |
Value
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by workflow
When split_by is provided:
-
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments for all columns (x,split_by,facet_by,group_by). The
split_bycolumn is validated and its NA / empty levels are processed. It is then removed from the per-columnkeep_na/keep_emptylists.The data is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
BarPlotAtomic()is called for each split. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
When split_by is provided:
-
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments. The
split_bycolumn is validated and its NA / empty levels are processed. It is then removed from the per-column lists.The data is split by
split_by(preserving level order).Per-split
palette,palcolor,legend.position, andlegend.directionare resolved.-
SplitBarPlotAtomic()is called for each split. Whentitleis a function, it receives the split level name for dynamic title generation. Results are combined via
combine_plots().
Examples
data <- data.frame(
x = c("A", "B", "C", "D", "E", "F", "G", "H"),
y = c(10, 8, 16, 4, 6, 12, 14, 2),
group = c("G1", "G1", "G2", "G2", "G3", "G3", "G4", "G4"),
facet = c("F1", "F2", "F3", "F4", "F1", "F2", "F3", "F4")
)
# Single-colour bars
BarPlot(data, x = "x", y = "y")
# Solid fill (no colour mapping)
BarPlot(data, x = "x", y = "y", fill_by = FALSE)
# Label bar tops
BarPlot(data, x = "x", y = "y", label = TRUE)
BarPlot(data, x = "x", y = "y", label = "facet", label_nudge = 0)
# Grouped bars
BarPlot(data, x = "group", y = "y", group_by = "x")
# Dodged bars with background stripes
BarPlot(data,
x = "group", y = "y", group_by = "x",
position = "dodge", add_bg = TRUE)
# split_by with faceting
BarPlot(data,
x = "x", y = "y", split_by = "group",
facet_by = "facet", position = "dodge", facet_ncol = 1)
# split_by with collected guides
BarPlot(data,
x = "x", y = "y", split_by = "group", facet_by = "facet",
position = "dodge", facet_ncol = 1, guides = 'collect')
# Per-split palettes
BarPlot(data,
x = "x", y = "y", split_by = "group",
palette = list(G1 = "Reds", G2 = "Blues", G3 = "Greens", G4 = "Purp"),
facet_by = "facet", position = "dodge", facet_ncol = 1)
# Background stripe palette
BarPlot(data,
x = "group", y = "y", group_by = "x",
position = "dodge", add_bg = TRUE, bg_palette = "Spectral")
# Count bars (y = NULL)
BarPlot(data, x = "group", ylab = "count")
# Flipped axes
BarPlot(data, x = "group", flip = TRUE, ylab = "count")
# Numeric fill_by with colour gradient
BarPlot(data, x = "x", y = "y", fill_by = "y", flip = TRUE)
# Control fill colour scale limits (quantile)
BarPlot(data, x = "x", y = "y", fill_by = "y", flip = TRUE,
lower_quantile = 0.1, upper_quantile = 0.9)
# Control fill colour scale limits (explicit cutoff)
BarPlot(data, x = "x", y = "y", fill_by = "y", flip = TRUE,
lower_cutoff = 5, upper_cutoff = 12)
# keep_na and keep_empty examples
data <- data.frame(
x = factor(c("A", "B", "C", "D", "E", "F", NA, "H"),
levels = LETTERS[1:10]),
y = c(10, 8, 16, 4, 6, NA, 14, 2),
group = factor(c("G1", "G1", "G2", NA, "G3", "G3", "G5", "G5"),
levels = c("G1", "G2", "G3", "G4", "G5")),
facet = factor(c("F1", NA, "F3", "F4", "F1", "F2", "F3", "F4"),
levels = c("F1", "F2", "F3", "F4", "F5"))
)
# Default: NA and empty levels dropped
BarPlot(data, x = "x", y = "y")
# Keep both NA and empty levels
BarPlot(data, x = "x", y = "y",
keep_na = TRUE, keep_empty = TRUE)
# With faceting
BarPlot(data, x = "x", y = "y",
keep_na = TRUE, keep_empty = TRUE, facet_by = "facet")
# Keep NA, hide empty levels but reserve their colours
BarPlot(data, x = "x", y = "y",
keep_na = TRUE, keep_empty = 'level')
# Per-column keep_na / keep_empty
BarPlot(data, x = "x", y = "y",
keep_na = list(x = TRUE), keep_empty = list(x = FALSE))
# Grouped bars with keep_na / keep_empty
BarPlot(data, x = "group", y = "y", group_by = "x")
BarPlot(data, x = "group", y = "y", group_by = "x",
keep_na = TRUE, keep_empty = TRUE)
BarPlot(data, x = "group", y = "y", group_by = "x",
keep_na = TRUE, keep_empty = TRUE, facet_by = "facet")
# Per-column on grouped bars
BarPlot(data, x = "group", y = "y", group_by = "x",
keep_na = list(x = TRUE, group = FALSE),
keep_empty = list(x = FALSE, group = TRUE))
set.seed(8525)
data <- data.frame(
word = c("apple", "banana", "cherry", "date", "elderberry",
"It is a very long term with a lot of words"),
count = c(-10, 20, -30, 40, 50, 34),
score = c(1, 2, 3, 4, 5, 3.2),
group = c("A", "A", "B", "B", "C", "C")
)
# Basic split bar plot with alpha encoding
SplitBarPlot(data, x = "count", y = "word", alpha_by = "score")
# Control label wrapping
SplitBarPlot(data, x = "count", y = "word", alpha_by = "score",
max_charwidth = 30, lineheight = 1.1)
# Fill by categorical variable
SplitBarPlot(data, x = "count", y = "word", fill_by = "group")
# Faceting
SplitBarPlot(data, x = "count", y = "word", facet_by = "group",
fill_name = "Direction")
# Per-split palettes
SplitBarPlot(data, x = "count", y = "word", alpha_by = "score",
split_by = "group",
palette = c(A = "Reds", B = "Blues", C = "Greens"))
# keep_na and keep_empty examples
data <- data.frame(
word = factor(c("apple", "banana", "cherry", NA, "elderberry",
"It is a very long term with a lot of words"),
levels = c("apple", "banana", "cherry", "date", "elderberry",
"unused", "It is a very long term with a lot of words")),
count = c(-10, 20, NA, 40, 10, 34),
score = c(1, 2, 3, 4, 5, 3.2),
group = factor(sample(c("A", "A", "B", "B", "C", "C")),
levels = c("A", "B", "C", "D"))
)
# Default: NA and empty levels dropped
SplitBarPlot(data, x = "count", y = "word", alpha_by = "score")
# Keep NA and empty levels
SplitBarPlot(data, x = "count", y = "word", alpha_by = "score",
keep_na = TRUE, keep_empty = TRUE)
# Keep with faceting
SplitBarPlot(data, x = "count", y = "word", alpha_by = "score",
keep_na = TRUE, keep_empty = TRUE, facet_by = "group")
# Keep NA, hide empty levels (reserve colours)
SplitBarPlot(data, x = "count", y = "word", alpha_by = "score",
keep_na = TRUE, keep_empty = "level")
# Per-column control
SplitBarPlot(data, x = "count", y = "word", alpha_by = "score",
keep_na = list(word = FALSE), keep_empty = list(word = TRUE))
# Control fill colour scale limits
SplitBarPlot(data, x = "count", y = "word", fill_by = "score",
lower_cutoff = 1, upper_cutoff = 4)
Atomic bar plot (internal)
Description
Dispatcher that routes to BarPlotSingle (when
group_by = NULL) or BarPlotGrouped (when
group_by is provided). This is the core implementation layer —
it takes a single data frame (no split_by support) and returns
a ggplot object with faceting applied.
Usage
BarPlotAtomic(
data,
x,
x_sep = "_",
y = NULL,
scale_y = FALSE,
flip = FALSE,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
fill_by = TRUE,
fill_name = NULL,
label_nudge = 0.02,
label = NULL,
label_fg = "black",
label_size = 4,
label_bg = "white",
label_bg_r = 0.1,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
theme = "theme_this",
theme_args = list(),
palette = NULL,
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
x_text_angle = 0,
aspect.ratio = 1,
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
line_name = NULL,
add_trend = FALSE,
trend_color = "black",
trend_linewidth = 1,
trend_ptsize = 2,
position = "auto",
position_dodge_preserve = "total",
y_min = NULL,
y_max = NULL,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
expand = waiver(),
width = waiver(),
facet_by = NULL,
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
facet_args = list(),
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
x_sep |
A character string to join multiple |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
scale_y |
A logical value. When |
flip |
Logical; if |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string for the group fill legend title.
When |
fill_by |
A variable used to fill the bars. Both categorical and numeric columns are accepted:
Ignored when |
fill_name |
A character string for the fill legend title. Only
applies when |
label_nudge |
A numeric value controlling the distance between labels and the bar top, expressed as a fraction of the data range. |
label |
A column name (or |
label_fg |
A character string specifying the label text colour. |
label_size |
A numeric value specifying the label text size. |
label_bg |
A character string specifying the label background colour. |
label_bg_r |
A numeric value specifying the label background corner radius. |
add_bg |
Logical; add alternating background stripes behind the bars. |
bg_palette |
Palette for the background stripes. |
bg_palcolor |
Custom colours for the background stripes. |
bg_alpha |
Alpha transparency for the background stripes. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
add_line |
A numeric y-intercept for a horizontal reference line. |
line_color |
Colour of the reference line. |
line_width |
Width of the reference line. |
line_type |
Linetype of the reference line (e.g., 1 = solid, 2 = dashed). |
line_name |
Legend name for the reference line. |
add_trend |
Logical; add a trend line and points connecting the bar tops. |
trend_color |
Colour of the trend line. |
trend_linewidth |
Width of the trend line. |
trend_ptsize |
Size of the trend line points. |
position |
A character string specifying the bar layout:
|
position_dodge_preserve |
A character string passed to
|
y_min, y_max |
Numeric limits for the y-axis (or x-axis when flipped). |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
width |
A numeric value specifying the bar width (0–1). |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
facet_args |
A list of additional arguments passed to the faceting
function (e.g., |
... |
Additional arguments. |
Value
A ggplot object, possibly faceted, with height
and width attributes (in inches) attached.
Dispatch logic
-
Without
group_by— delegates toBarPlotSingle.fill_bycontrols bar colouring:TRUE(default) fills by x-axis values,FALSEuses a single colour, a character column produces discrete colours, and a numeric column produces a continuous gradient. -
With
group_by— delegates toBarPlotGrouped.fill_bymust matchgroup_byor be left as default; an explicit mismatch raises a stop error.positioncontrols dodge vs. stack layout with automatic selection based on group count (\le5 → dodge, >5 → stack).
After the delegate returns, facet_plot() wraps the result
with facet_wrap / facet_grid if facet_by is provided.
Bar plot with groups
Description
Core implementation for drawing a grouped bar plot. Each x-axis category
is split into side-by-side (dodge) or stacked bars according to the
group_by variable. This is the grouped code path dispatched by
BarPlotAtomic when group_by is provided.
Usage
BarPlotGrouped(
data,
x,
x_sep = "_",
y = NULL,
scale_y = FALSE,
flip = FALSE,
group_by,
group_by_sep = "_",
group_name = NULL,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
label = NULL,
label_nudge = 0.02,
label_fg = "black",
label_size = 4,
label_bg = "white",
label_bg_r = 0.1,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
alpha = 1,
x_text_angle = 0,
aspect.ratio = 1,
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
line_name = NULL,
add_trend = FALSE,
trend_color = "black",
trend_linewidth = 1,
trend_ptsize = 2.5,
position = "auto",
position_dodge_preserve = "total",
y_min = NULL,
y_max = NULL,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
expand = waiver(),
width = 0.8,
facet_by = NULL,
facet_scales = "fixed",
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
x_sep |
A character string to join multiple |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
scale_y |
A logical value. When |
flip |
Logical; if |
group_by |
A character vector of column name(s) to group the bars by.
Each unique combination becomes a separate bar segment. Multiple columns
are concatenated with |
group_by_sep |
A character string to separate concatenated
|
group_name |
A character string for the group fill legend title.
When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
label |
A column name (or |
label_nudge |
A numeric value controlling the distance between labels and the bar top, expressed as a fraction of the data range. |
label_fg |
A character string specifying the label text colour. |
label_size |
A numeric value specifying the label text size. |
label_bg |
A character string specifying the label background colour. |
label_bg_r |
A numeric value specifying the label background corner radius. |
add_bg |
Logical; add alternating background stripes behind the bars. |
bg_palette |
Palette for the background stripes. |
bg_palcolor |
Custom colours for the background stripes. |
bg_alpha |
Alpha transparency for the background stripes. |
alpha |
A numeric value specifying the transparency of the plot. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
add_line |
A numeric y-intercept for a horizontal reference line. |
line_color |
Colour of the reference line. |
line_width |
Width of the reference line. |
line_type |
Linetype of the reference line (e.g., 1 = solid, 2 = dashed). |
line_name |
Legend name for the reference line. |
add_trend |
Logical; add a trend line and points connecting the bar tops. |
trend_color |
Colour of the trend line. |
trend_linewidth |
Width of the trend line. |
trend_ptsize |
Size of the trend line points. |
position |
A character string specifying the bar layout:
|
position_dodge_preserve |
A character string passed to
|
y_min, y_max |
Numeric limits for the y-axis (or x-axis when flipped). |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
width |
A numeric value specifying the bar width (0–1). |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
Column resolution —
group_by,facet_by,x, andyare validated and transformed viacheck_columns. -
Count aggregation — when
y = NULL, the count of observations per (x,group_by,facet_by) combination is computed. Factor levels are preserved. -
Proportion scaling — when
scale_y = TRUE, y-values are divided by the sum within each (x,facet_by) group so that each x position stacks to 100\ -
Position resolution —
position = "auto"chooses"dodge"for\le5 groups or"stack"for >5 groups. Explicit"dodge"and"stack"are also accepted. -
Expand calculation — for stacked bars, expansion is computed from y-range and label presence. For dodged bars, expansion is minimal. The
norm_expansion()utility normalises the final expansion vector. -
Colour mapping —
palette_this()assigns per-group colours. The fill scaledropargument is controlled bykeep_empty_group. -
Labels — when
labelis set:For stacked bars, cumulative label positions are computed so each label is centred within its segment.
For dodged bars, labels are nudged above/below the bar top by
label_nudge× the data range.-
geom_text_repel()is used for automatic overlap avoidance.
-
Trend line — when
add_trend = TRUE, lines connect bar tops. Whentrend_colorisNULL, each group gets its own coloured line; otherwise a single colour is used. -
Horizontal reference line —
add_linedraws ageom_hline()at the specified y-value. -
Dimension calculation — width accounts for the number of x categories × number of groups (dodge) or just x categories (stack).
calculate_plot_dimensions()adjusts forflipand legend metrics. -
Coordinate transform —
coord_flip()orcoord_cartesian()withy_min/y_max.
Single bar plot (no groups)
Description
Core implementation for drawing a bar plot without grouping — each x-axis
category is a single bar. This is the simpler code path dispatched by
BarPlotAtomic when group_by = NULL. Bars can be
filled by a categorical variable, a continuous variable (numeric colour
gradient), or a solid colour.
Usage
BarPlotSingle(
data,
x,
x_sep = "_",
y = NULL,
flip = FALSE,
facet_by = NULL,
facet_scales = "fixed",
label = NULL,
label_nudge = 0.02,
label_fg = "black",
label_size = 4,
label_bg = "white",
label_bg_r = 0.1,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
theme = "theme_this",
theme_args = list(),
palette = NULL,
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
x_text_angle = 0,
aspect.ratio = 1,
y_min = NULL,
y_max = NULL,
legend.position = "right",
legend.direction = "vertical",
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
line_name = NULL,
add_trend = FALSE,
trend_color = "black",
trend_linewidth = 1,
trend_ptsize = 2.5,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
expand = waiver(),
fill_by = TRUE,
fill_name = NULL,
width = 0.9,
...
)
Arguments
data |
A data frame. |
x |
A character vector of column name(s) for the x-axis.
Character/factor columns are expected. Multiple columns are
concatenated with |
x_sep |
A character string to join multiple |
y |
A character string specifying the numeric column for the y-axis.
Default |
flip |
Logical; if |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
label |
A column name (or |
label_nudge |
A numeric value controlling the distance between labels and the bar top, expressed as a fraction of the data range. |
label_fg |
A character string specifying the label text colour. |
label_size |
A numeric value specifying the label text size. |
label_bg |
A character string specifying the label background colour. |
label_bg_r |
A numeric value specifying the label background corner radius. |
add_bg |
Logical; add alternating background stripes behind the bars. |
bg_palette |
Palette for the background stripes. |
bg_palcolor |
Custom colours for the background stripes. |
bg_alpha |
Alpha transparency for the background stripes. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
y_min, y_max |
Numeric limits for the y-axis (or x-axis when flipped). |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
add_line |
A numeric y-intercept for a horizontal reference line. |
line_color |
Colour of the reference line. |
line_width |
Width of the reference line. |
line_type |
Linetype of the reference line (e.g., 1 = solid, 2 = dashed). |
line_name |
Legend name for the reference line. |
add_trend |
Logical; add a trend line and points connecting the bar tops. |
trend_color |
Colour of the trend line. |
trend_linewidth |
Width of the trend line. |
trend_ptsize |
Size of the trend line points. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
fill_by |
A variable used to fill the bars. Can be |
fill_name |
A character string for the fill legend title. |
width |
A numeric value specifying the bar width (0–1). |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
Column resolution —
x,y, andfacet_byare validated and transformed viacheck_columns. Multi-columnxis concatenated withx_sep. -
Count aggregation — when
y = NULL, the count of observations per (x,facet_by) combination is computed as a new.ycolumn. Factor levels are preserved. -
Fill resolution —
fill_bycan beTRUE(use x values),FALSE/NULL(solid fill), a categorical column name (discrete colour scale), or a numeric column name (continuous gradient). Discrete fills usepalette_this()for colour assignment; numeric fills useprepare_continuous_color_scale()with quantile / cutoff clamping andscale_fill_gradientn(). -
Background stripes — when
add_bg = TRUE,bg_layer()adds alternating horizontal or vertical stripe fills behind the bars. -
Labels — when
labelis set, values are displayed on or near the bar tops viageom_text_repel()(non-flipped) orgeom_text()(flipped). The y-position is nudged bylabel_nudge× the data range. -
Trend line — when
add_trend = TRUE, a line and points are overlaid across the bar tops. -
Horizontal reference line —
add_linedraws a horizontal line at the specified y-value, with a colour legend entry named byline_name. -
Dimension calculation —
calculate_plot_dimensions()computes plot height and width from the x-axis category count, label character widths, legend metrics, and flip state. When flipped, height scales with the number of x categories. -
Coordinate transform — when
flip = TRUE,coord_flip()swaps axes; otherwisecoord_cartesian()appliesy_min/y_maxlimits. Free-scale faceting skips limit constraints.
Box / Violin / Bar / Beeswarm plot
Description
BoxPlot draws box plots or bar plots (mean ± error bars) with extensive
customisation options. Supports jittered or beeswarm points, paired
observations with connecting lines, trend lines, statistical test
annotations (pairwise or omnibus), background stripes, reference lines,
point highlighting, and custom summary statistic overlays.
This is the public API — it delegates to BoxViolinPlot
with base = "box" or base = "bar", which in turn dispatches
to BoxViolinPlotAtomic for each split_by level.
ViolinPlot draws violin plots with extensive customisation options. Supports jittered
or beeswarm points, box plot overlays, trend lines, statistical test
annotations, background stripes, reference lines, point highlighting,
and custom summary statistic overlays.
This is the public API — it delegates to BoxViolinPlot
with base = "violin", which dispatches to
BoxViolinPlotAtomic for each split_by level.
BeeswarmPlot draws beeswarm plots — points arranged by the beeswarm algorithm to
avoid overlap while displaying the distribution density. This is a
convenience wrapper that delegates to BoxViolinPlot with
base = "none" and add_beeswarm = TRUE.
Requires the ggbeeswarm package. To get a beeswarm plot WITH a
box plot, use BeeswarmPlot(..., add_box = TRUE). To get a violin
plot with beeswarm points, use ViolinPlot(..., add_beeswarm = TRUE).
Usage
BoxPlot(
data,
x,
x_sep = "_",
y = NULL,
base = c("box", "bar"),
in_form = c("long", "wide"),
split_by = NULL,
split_by_sep = "_",
symnum_args = NULL,
sort_x = NULL,
flip = FALSE,
keep_empty = FALSE,
keep_na = FALSE,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
paired_by = NULL,
x_text_angle = ifelse(isTRUE(flip), 0, 45),
step_increase = 0.1,
fill_mode = ifelse(!is.null(group_by), "dodge", "x"),
palreverse = FALSE,
position_dodge_preserve = "total",
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
alpha = 1,
aspect.ratio = NULL,
legend.position = "right",
legend.direction = "vertical",
add_point = FALSE,
pt_color = if (isTRUE(add_beeswarm)) NULL else "grey30",
pt_size = NULL,
pt_alpha = 1,
jitter_width = NULL,
jitter_height = 0,
stack = FALSE,
y_max = NULL,
y_min = NULL,
y_brackets = NULL,
add_beeswarm = FALSE,
beeswarm_method = "swarm",
beeswarm_cex = 1,
beeswarm_priority = "ascending",
beeswarm_dodge = 0.9,
add_trend = FALSE,
trend_color = NULL,
trend_linewidth = 1,
trend_ptsize = 2,
add_stat = NULL,
stat_name = NULL,
stat_color = "black",
stat_size = 1,
stat_stroke = 1,
stat_shape = 25,
add_errorbar = "SEM",
errorbar_color = "grey20",
errorbar_width = 0.4,
errorbar_linewidth = 0.6,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
highlight = NULL,
highlight_color = "red2",
highlight_size = 1,
highlight_alpha = 1,
comparisons = NULL,
ref_group = NULL,
pairwise_method = "wilcox.test",
multiplegroup_comparisons = FALSE,
multiple_method = "kruskal.test",
sig_label = "p.format",
sig_labelsize = 3.5,
hide_ns = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
...
)
ViolinPlot(
data,
x,
x_sep = "_",
y = NULL,
in_form = c("long", "wide"),
split_by = NULL,
split_by_sep = "_",
symnum_args = NULL,
sort_x = NULL,
flip = FALSE,
keep_empty = FALSE,
keep_na = FALSE,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
paired_by = NULL,
x_text_angle = ifelse(isTRUE(flip), 0, 45),
step_increase = 0.1,
fill_mode = ifelse(!is.null(group_by), "dodge", "x"),
palreverse = FALSE,
position_dodge_preserve = "total",
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
alpha = 1,
aspect.ratio = NULL,
legend.position = "right",
legend.direction = "vertical",
add_point = FALSE,
pt_color = if (isTRUE(add_beeswarm)) NULL else "grey30",
pt_size = NULL,
pt_alpha = 1,
jitter_width = NULL,
jitter_height = 0,
stack = FALSE,
y_max = NULL,
y_min = NULL,
y_brackets = NULL,
add_beeswarm = FALSE,
beeswarm_method = "swarm",
beeswarm_cex = 1,
beeswarm_priority = "ascending",
beeswarm_dodge = 0.9,
add_box = FALSE,
box_color = "black",
box_width = 0.1,
box_ptsize = 2.5,
add_trend = FALSE,
trend_color = NULL,
trend_linewidth = 1,
trend_ptsize = 2,
add_stat = NULL,
stat_name = NULL,
stat_color = "black",
stat_size = 1,
stat_stroke = 1,
stat_shape = 25,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
highlight = NULL,
highlight_color = "red2",
highlight_size = 1,
highlight_alpha = 1,
comparisons = NULL,
ref_group = NULL,
pairwise_method = "wilcox.test",
multiplegroup_comparisons = FALSE,
multiple_method = "kruskal.test",
sig_label = "p.format",
sig_labelsize = 3.5,
hide_ns = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
...
)
BeeswarmPlot(
data,
x,
x_sep = "_",
y = NULL,
in_form = c("long", "wide"),
split_by = NULL,
split_by_sep = "_",
symnum_args = NULL,
sort_x = NULL,
flip = FALSE,
keep_empty = FALSE,
keep_na = FALSE,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
paired_by = NULL,
x_text_angle = ifelse(isTRUE(flip), 0, 45),
step_increase = 0.1,
fill_mode = ifelse(!is.null(group_by), "dodge", "x"),
palreverse = FALSE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
alpha = 1,
aspect.ratio = NULL,
legend.position = "right",
legend.direction = "vertical",
pt_color = NULL,
pt_size = NULL,
pt_alpha = 1,
position_dodge_preserve = "total",
jitter_width = NULL,
jitter_height = 0,
stack = FALSE,
y_max = NULL,
y_min = NULL,
y_brackets = NULL,
add_violin = FALSE,
beeswarm_method = "swarm",
beeswarm_cex = 1,
beeswarm_priority = "ascending",
beeswarm_dodge = 0.9,
add_box = FALSE,
box_color = "black",
box_width = 0.1,
box_ptsize = 2.5,
add_trend = FALSE,
trend_color = NULL,
trend_linewidth = 1,
trend_ptsize = 2,
add_stat = NULL,
stat_name = NULL,
stat_color = "black",
stat_size = 1,
stat_stroke = 1,
stat_shape = 25,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
highlight = NULL,
highlight_color = "red2",
highlight_size = 1,
highlight_alpha = 1,
comparisons = NULL,
ref_group = NULL,
pairwise_method = "wilcox.test",
multiplegroup_comparisons = FALSE,
multiple_method = "kruskal.test",
sig_label = "p.format",
sig_labelsize = 3.5,
hide_ns = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
x_sep |
A character string to join multiple |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
base |
A character string: |
in_form |
A character string: |
split_by |
The column(s) to split the data by for separate sub-plots. |
split_by_sep |
Separator for concatenated |
symnum_args |
A list of arguments passed to
|
sort_x |
An R expression string (e.g., |
flip |
Logical; if |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string for the dodge legend title. |
paired_by |
A character string naming a column that identifies
paired observations. Forces |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
step_increase |
Fractional step increase for stacking significance brackets when multiple comparisons exist. |
fill_mode |
A character string controlling fill colour mapping:
|
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
position_dodge_preserve |
Passed to
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
add_point |
Logical; add jittered or beeswarm points to the plot. |
pt_color |
Colour of the points. When |
pt_size |
Numeric size of the points. Default computed from
data size: |
pt_alpha |
Numeric transparency of the points. |
jitter_width |
Numeric width of the jitter. Defaults to
|
jitter_height |
Numeric height of the jitter. Default |
stack |
Logical; stack facetted panels in a compact layout with shared strip labels. |
y_max, y_min |
Numeric y-axis limits, or quantile notation strings
(e.g., |
y_brackets |
Numeric y-axis position for significance brackets (or p-value labels for multiple comparisons). If NULL, the brackets are placed above the maximum y-value. |
add_beeswarm |
Logical; use |
beeswarm_method |
Beeswarm layout method: |
beeswarm_cex |
Numeric scaling for point spacing. Larger values spread points more. |
beeswarm_priority |
Point layout priority: |
beeswarm_dodge |
Numeric dodge width for beeswarm points when
|
add_trend |
Logical; add trend lines connecting group medians. |
trend_color |
Colour of the trend line. When |
trend_linewidth |
Width of the trend line. |
trend_ptsize |
Size of the trend line points. |
add_stat |
A summary function (e.g., |
stat_name |
Legend title for the stat summary shape. |
stat_color |
Colour of the stat summary point. |
stat_size |
Size of the stat summary point. |
stat_stroke |
Stroke width of the stat summary point. |
stat_shape |
Shape (an integer) for the stat summary point. Uses
|
add_errorbar |
Type of error bars for bar plots. See Details. |
errorbar_color, errorbar_width, errorbar_linewidth |
Error bar appearance controls. |
add_bg |
Logical; add alternating background stripes. |
bg_palette |
Palette for the background stripes. |
bg_palcolor |
Custom colours for the background stripes. |
bg_alpha |
Alpha transparency for the background stripes. |
add_line |
A numeric y-intercept for a horizontal reference line. |
line_color |
Colour of the reference line. |
line_width |
Width of the reference line. |
line_type |
Linetype of the reference line. |
highlight |
A specification of points to highlight: |
highlight_color |
Colour of highlighted points. |
highlight_size |
Size of highlighted points. |
highlight_alpha |
Alpha of highlighted points. |
comparisons |
A logical value ( |
ref_group |
A character string specifying the reference group for comparisons. |
pairwise_method |
Method for pairwise tests. Default
|
multiplegroup_comparisons |
Logical; perform an omnibus test (e.g., Kruskal-Wallis) across all groups. |
multiple_method |
Method for the omnibus test. Default
|
sig_label |
Label format for significance annotations. For
pairwise comparisons: |
sig_labelsize |
Size of the significance label text. |
hide_ns |
Logical; hide non-significant comparison labels. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
A numeric seed for reproducibility. |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout. |
byrow |
Logical; fill the combined layout by row (default |
axes, axis_titles |
Character strings for axis handling in the combined layout. |
guides |
Character string for legend collection across panels. |
... |
Additional arguments. |
add_box |
Logical; overlay a box plot on the primary geometry.
Mutually exclusive with |
box_color |
Colour of the overlaid box plot outline and fill. |
box_width |
Width of the overlaid box plot. |
box_ptsize |
Size of the median point in the overlaid box plot. |
add_violin |
Logical; whether to add a violin plot behind the
beeswarm points. Not supported — the function will stop with an
error directing you to use |
Value
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
Bar plots (base = "bar")
When base = "bar", bars display group means with optional error
bars. add_errorbar controls the error bar type:
-
"SEM"(default) — standard error of the mean. -
"SD"— standard deviation. -
"CI"or"CI95"— 95\ -
"none"— no error bars.
Error bars are computed via a custom stat_summary(fun.data = ...)
that handles per-group mean, SD, and sample size.
Examples
set.seed(8525)
data <- data.frame(
x = rep(LETTERS[1:8], each = 40),
y = c(rnorm(160), rnorm(160, mean = 1)),
group1 = sample(c("g1", "g2"), 320, replace = TRUE),
group2 = sample(c("h1", "h2", "h3", "h4"), 320, replace = TRUE)
)
# Basic box plot
BoxPlot(data, x = "x", y = "y")
# With beeswarm points
BoxPlot(data, x = "x", y = "y", add_beeswarm = TRUE, pt_color = "grey30")
# Stacked + flipped + faceted
BoxPlot(data,
x = "x", y = "y",
stack = TRUE, flip = TRUE, facet_by = "group1",
add_bg = TRUE, bg_palette = "Paired")
# Stacked + flipped + split_by with per-split colours
BoxPlot(data,
x = "x", y = "y",
stack = TRUE, flip = TRUE, split_by = "group1",
add_bg = TRUE, bg_palette = "Paired",
palcolor = list(g1 = c("red", "blue"), g2 = c("blue", "red")))
# sort_x — order by mean(y)
data <- data.frame(
x = factor(rep(LETTERS[1:5], each = 40),
levels = c(LETTERS[1:2], "unused", LETTERS[3:5])),
y = c(rnorm(40, mean = 5), rnorm(40, mean = 4), rnorm(40, mean = 3),
rnorm(40, mean = 2), rnorm(40, mean = 1))
)
BoxPlot(data, x = "x", y = "y", sort_x = "mean(y)", keep_empty = TRUE)
BoxPlot(data, x = "x", y = "y", sort_x = "mean(-y)", keep_empty = TRUE)
# Wide-form data
data_wide <- data.frame(A = rnorm(100), B = rnorm(100), C = rnorm(100))
BoxPlot(data_wide, x = c("A", "B", "C"), in_form = "wide")
# Paired observations with connecting lines and paired test
paired_data <- data.frame(
subject = rep(paste0("s", 1:10), each = 2),
visit = rep(c("pre", "post"), times = 10),
value = rnorm(20))
BoxPlot(paired_data,
x = "visit", y = "value", comparisons = TRUE,
paired_by = "subject", add_point = TRUE)
# Paired + grouped
paired_group_data <- data.frame(
subject = rep(paste0("s", 1:6), each = 2),
x = rep(c("A", "B"), each = 6),
group = rep(c("before", "after"), times = 6),
value = rnorm(12))
BoxPlot(paired_group_data,
x = "x", y = "value",
paired_by = "subject", group_by = "group",
comparisons = TRUE, pt_size = 3, pt_color = "red")
# keep_na and keep_empty examples
data <- data.frame(
x = factor(rep(c(LETTERS[1:3], NA, LETTERS[5:8]), each = 40),
levels = c(LETTERS[1:8])),
y = c(rnorm(160), rnorm(160, mean = 1)),
group1 = sample(c("g1", "g2"), 320, replace = TRUE),
group2 = factor(sample(c("h1", NA, "h3", "h4"), 320, replace = TRUE),
levels = c("h1", "h2", "h3", "h4")))
BoxPlot(data, x = "x", y = "y")
BoxPlot(data, x = "x", y = "y", keep_na = TRUE, keep_empty = TRUE)
BoxPlot(data, x = "x", y = "y", keep_na = TRUE, keep_empty = TRUE,
facet_by = "group2")
BoxPlot(data, x = "x", y = "y", keep_na = TRUE, keep_empty = 'level')
BoxPlot(data, x = "x", y = "y", group_by = "group2")
BoxPlot(data, x = "x", y = "y", group_by = "group2",
keep_na = TRUE, keep_empty = TRUE)
BoxPlot(data, x = "x", y = "y", group_by = "group2",
keep_na = TRUE, keep_empty = 'level')
# Per-column keep_na / keep_empty
BoxPlot(data, x = "x", y = "y", group_by = "group2",
keep_na = list(x = TRUE, group2 = FALSE),
keep_empty = list(x = FALSE, group2 = TRUE))
# Bar plot (base = "bar")
data$y <- abs(data$y)
BoxPlot(data, x = "x", y = "y", base = "bar")
BoxPlot(data, x = "x", y = "y", base = "bar", add_errorbar = "SD")
BoxPlot(data, x = "x", y = "y", base = "bar", add_errorbar = "CI95")
BoxPlot(data, x = "x", y = "y", base = "bar", add_errorbar = "none")
BoxPlot(data, x = "x", y = "y", base = "bar", group_by = "group1")
BoxPlot(data, x = "x", y = "y", base = "bar", add_point = TRUE)
BoxPlot(data, x = "x", y = "y", base = "bar",
fill_mode = "mean", palette = "Blues")
ViolinPlot(data, x = "x", y = "y")
ViolinPlot(data, x = "x", y = "y", add_beeswarm = TRUE, pt_color = "grey30")
ViolinPlot(data, x = "x", y = "y", add_box = TRUE)
ViolinPlot(data, x = "x", y = "y", add_point = TRUE)
ViolinPlot(data, x = "x", y = "y", add_trend = TRUE)
ViolinPlot(data, x = "x", y = "y", add_stat = mean)
ViolinPlot(data, x = "x", y = "y", add_bg = TRUE)
ViolinPlot(data, x = "x", y = "y", add_line = 0)
# Grouped
ViolinPlot(data, x = "x", y = "y", group_by = "group1")
# Grouped + faceted + box overlay
ViolinPlot(data,
x = "x", y = "y", group_by = "group1",
facet_by = "group2", add_box = TRUE)
# Highlight
ViolinPlot(data,
x = "x", y = "y", add_point = TRUE,
highlight = 'group1 == "g1"', alpha = 0.8,
highlight_size = 1.5, pt_size = 1, add_box = TRUE)
# Pairwise comparisons with formatted labels
if (requireNamespace("ggpubr", quietly = TRUE)) {
# https://github.com/kassambara/ggpubr/issues/751
library(ggpubr)
ViolinPlot(data,
x = "x", y = "y", group_by = "group1",
comparisons = TRUE, sig_label = "p = {p}")
}
# Explicit comparison list + hide non-significant
ViolinPlot(data,
x = "x", y = "y", sig_label = "p.format", hide_ns = TRUE,
facet_by = "group2", comparisons = list(c("D", "E")))
# Continuous fill (mean) + omnibus test
ViolinPlot(data,
x = "x", y = "y", fill_mode = "mean",
facet_by = "group2", palette = "Blues",
multiplegroup_comparisons = TRUE)
# Per-split palettes
ViolinPlot(data,
x = "x", y = "y", fill_mode = "mean",
split_by = "group1", palette = c(g1 = "Blues", g2 = "Reds"))
# Stacked faceting
ViolinPlot(data,
x = "x", y = "y", stack = TRUE,
facet_by = "group2", add_box = TRUE, add_bg = TRUE,
bg_palette = "Paired")
# Basic beeswarm
BeeswarmPlot(data, x = "x", y = "y")
# Control point size
BeeswarmPlot(data, x = "x", y = "y", pt_size = 1)
# Beeswarm with box overlay
BeeswarmPlot(data, x = "x", y = "y", add_box = TRUE, pt_color = "grey30")
# Grouped
BeeswarmPlot(data, x = "x", y = "y", group_by = "group1")
# Grouped without dodging
BeeswarmPlot(data, x = "x", y = "y", group_by = "group1",
beeswarm_dodge = NULL)
# Hex layout with wider spacing
BeeswarmPlot(data,
x = "x", y = "y", beeswarm_method = "hex",
beeswarm_cex = 2)
Box / Violin / Bar / Beeswarm plot (internal)
Description
Internal wrapper that handles split_by processing and dispatches
to BoxViolinPlotAtomic for each split. This is the
intermediate layer between the three public APIs
(BoxPlot, ViolinPlot, and
BeeswarmPlot) and the core implementation.
Usage
BoxViolinPlot(
data,
x,
x_sep = "_",
y = NULL,
base = c("box", "violin", "bar", "none"),
in_form = c("long", "wide"),
split_by = NULL,
split_by_sep = "_",
symnum_args = NULL,
sort_x = NULL,
flip = FALSE,
keep_empty = FALSE,
keep_na = FALSE,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
paired_by = NULL,
x_text_angle = ifelse(isTRUE(flip), 0, 45),
step_increase = 0.1,
fill_mode = ifelse(!is.null(group_by), "dodge", "x"),
palreverse = FALSE,
position_dodge_preserve = "total",
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
alpha = 1,
aspect.ratio = NULL,
legend.position = "right",
legend.direction = "vertical",
add_point = FALSE,
pt_color = if (isTRUE(add_beeswarm)) NULL else "grey30",
pt_size = NULL,
pt_alpha = 1,
jitter_width = NULL,
jitter_height = 0,
stack = FALSE,
y_max = NULL,
y_min = NULL,
y_brackets = NULL,
add_beeswarm = FALSE,
beeswarm_method = "swarm",
beeswarm_cex = 1,
beeswarm_priority = "ascending",
beeswarm_dodge = 0.9,
add_box = FALSE,
box_color = "black",
box_width = 0.1,
box_ptsize = 2.5,
add_errorbar = "SEM",
errorbar_color = "grey20",
errorbar_width = 0.4,
errorbar_linewidth = 0.6,
add_trend = FALSE,
trend_color = NULL,
trend_linewidth = 1,
trend_ptsize = 2,
add_stat = NULL,
stat_name = NULL,
stat_color = "black",
stat_size = 1,
stat_stroke = 1,
stat_shape = 25,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
highlight = NULL,
highlight_color = "red2",
highlight_size = 1,
highlight_alpha = 1,
comparisons = NULL,
ref_group = NULL,
pairwise_method = "wilcox.test",
multiplegroup_comparisons = FALSE,
multiple_method = "kruskal.test",
sig_label = "p.format",
sig_labelsize = 3.5,
hide_ns = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
x_sep |
A character string to join multiple |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
base |
A character string specifying the primary plot type:
|
in_form |
A character string: |
split_by |
The column(s) to split the data by for separate sub-plots. |
split_by_sep |
Separator for concatenated |
symnum_args |
A list of arguments passed to
|
sort_x |
An R expression string (e.g., |
flip |
Logical; if |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string for the dodge legend title. |
paired_by |
A character string naming a column that identifies
paired observations. Forces |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
step_increase |
Fractional step increase for stacking significance brackets when multiple comparisons exist. |
fill_mode |
A character string controlling fill colour mapping:
|
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
position_dodge_preserve |
Passed to
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
add_point |
Logical; add jittered or beeswarm points to the plot. |
pt_color |
Colour of the points. When |
pt_size |
Numeric size of the points. Default computed from
data size: |
pt_alpha |
Numeric transparency of the points. |
jitter_width |
Numeric width of the jitter. Defaults to
|
jitter_height |
Numeric height of the jitter. Default |
stack |
Logical; stack facetted panels in a compact layout with shared strip labels. |
y_max, y_min |
Numeric y-axis limits, or quantile notation strings
(e.g., |
y_brackets |
Numeric y-axis position for significance brackets (or p-value labels for multiple comparisons). If NULL, the brackets are placed above the maximum y-value. |
add_beeswarm |
Logical; use |
beeswarm_method |
Beeswarm layout method: |
beeswarm_cex |
Numeric scaling for point spacing. Larger values spread points more. |
beeswarm_priority |
Point layout priority: |
beeswarm_dodge |
Numeric dodge width for beeswarm points when
|
add_box |
Logical; overlay a box plot on the primary geometry.
Mutually exclusive with |
box_color |
Colour of the overlaid box plot outline and fill. |
box_width |
Width of the overlaid box plot. |
box_ptsize |
Size of the median point in the overlaid box plot. |
add_errorbar |
Type of error bars for bar plots ( |
errorbar_color |
Colour of the error bar lines and caps. |
errorbar_width |
Width of the error bar caps. |
errorbar_linewidth |
Line width of the error bars. |
add_trend |
Logical; add trend lines connecting group medians. |
trend_color |
Colour of the trend line. When |
trend_linewidth |
Width of the trend line. |
trend_ptsize |
Size of the trend line points. |
add_stat |
A summary function (e.g., |
stat_name |
Legend title for the stat summary shape. |
stat_color |
Colour of the stat summary point. |
stat_size |
Size of the stat summary point. |
stat_stroke |
Stroke width of the stat summary point. |
stat_shape |
Shape (an integer) for the stat summary point. Uses
|
add_bg |
Logical; add alternating background stripes. |
bg_palette |
Palette for the background stripes. |
bg_palcolor |
Custom colours for the background stripes. |
bg_alpha |
Alpha transparency for the background stripes. |
add_line |
A numeric y-intercept for a horizontal reference line. |
line_color |
Colour of the reference line. |
line_width |
Width of the reference line. |
line_type |
Linetype of the reference line. |
highlight |
A specification of points to highlight: |
highlight_color |
Colour of highlighted points. |
highlight_size |
Size of highlighted points. |
highlight_alpha |
Alpha of highlighted points. |
comparisons |
A logical value ( |
ref_group |
A character string specifying the reference group for comparisons. |
pairwise_method |
Method for pairwise tests. Default
|
multiplegroup_comparisons |
Logical; perform an omnibus test (e.g., Kruskal-Wallis) across all groups. |
multiple_method |
Method for the omnibus test. Default
|
sig_label |
Label format for significance annotations. For
pairwise comparisons: |
sig_labelsize |
Size of the significance label text. |
hide_ns |
Logical; hide non-significant comparison labels. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
A numeric seed for reproducibility. |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout. |
byrow |
Logical; fill the combined layout by row (default |
axes, axis_titles |
Character strings for axis handling in the combined layout. |
guides |
Character string for legend collection across panels. |
design |
A custom layout design for the combined plot. |
... |
Additional arguments. |
Value
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by workflow
When split_by is provided:
-
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments. The
split_bycolumn is validated and its NA / empty levels are processed. It is then removed from the per-column lists.The data is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved.-
BoxViolinPlotAtomic()is called for each split. Whentitleis a function, it receives the split level name for dynamic titles. Results are combined via
combine_plots().
Atomic Box / Violin / Bar / Beeswarm plot (internal)
Description
Core implementation for drawing box plots, violin plots, bar plots (mean
± error bars), or beeswarm plots. This is the workhorse behind
BoxPlot, ViolinPlot, and
BeeswarmPlot — it takes a single data frame (no
split_by support) and returns a ggplot object.
The base parameter selects the primary geometry:
-
"box"—geom_boxplot() -
"violin"—geom_violin() -
"bar"—stat_summary(fun = mean, geom = "col")with optional error bars (SEM, SD, or CI). -
"none"— no primary geometry (used byBeeswarmPlotto draw beeswarm points alone).
Usage
BoxViolinPlotAtomic(
data,
x,
x_sep = "_",
y = NULL,
base = c("box", "violin", "bar", "none"),
in_form = c("long", "wide"),
sort_x = NULL,
flip = FALSE,
keep_empty = FALSE,
keep_na = FALSE,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
paired_by = NULL,
x_text_angle = ifelse(isTRUE(flip), 0, 45),
step_increase = 0.1,
position_dodge_preserve = "total",
fill_mode = ifelse(!is.null(group_by), "dodge", "x"),
palreverse = FALSE,
symnum_args = NULL,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
alpha = 1,
aspect.ratio = NULL,
legend.position = "right",
legend.direction = "vertical",
add_point = FALSE,
pt_color = if (isTRUE(add_beeswarm)) NULL else "grey30",
pt_size = NULL,
pt_alpha = 1,
y_nbreaks = 4,
jitter_width = NULL,
jitter_height = 0,
stack = FALSE,
y_max = NULL,
y_min = NULL,
y_trans = "identity",
y_brackets = NULL,
add_beeswarm = FALSE,
beeswarm_method = "swarm",
beeswarm_cex = 1,
beeswarm_priority = "ascending",
beeswarm_dodge = 0.9,
add_box = FALSE,
box_color = "black",
box_width = 0.1,
box_ptsize = 2.5,
add_errorbar = "SEM",
errorbar_color = "grey20",
errorbar_width = 0.4,
errorbar_linewidth = 0.6,
add_trend = FALSE,
trend_color = NULL,
trend_linewidth = 1,
trend_ptsize = 2,
add_stat = NULL,
stat_name = NULL,
stat_color = "black",
stat_size = 1,
stat_stroke = 1,
stat_shape = 25,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_line = NULL,
line_color = "red2",
line_width = 0.6,
line_type = 2,
highlight = NULL,
highlight_color = "red2",
highlight_size = 1,
highlight_alpha = 1,
comparisons = NULL,
ref_group = NULL,
pairwise_method = "wilcox.test",
multiplegroup_comparisons = FALSE,
multiple_method = "kruskal.test",
sig_label = "p.format",
sig_labelsize = 3.5,
hide_ns = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
...
)
Arguments
data |
A data frame. |
x |
A character string of column name(s) for the x-axis.
Character/factor columns are expected. Multiple columns are
concatenated with |
x_sep |
A character string to join multiple |
y |
A character string of the numeric column for the y-axis.
Not required when |
base |
A character string specifying the primary plot type:
|
in_form |
A character string: |
sort_x |
An R expression string (e.g., |
flip |
Logical; if |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
group_by |
A character vector of column name(s) to dodge the
boxes/violins by. Multiple columns are concatenated with
|
group_by_sep |
A character string to separate concatenated
|
group_name |
A character string for the dodge legend title. |
paired_by |
A character string naming a column that identifies
paired observations. Forces |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
step_increase |
Fractional step increase for stacking significance brackets when multiple comparisons exist. |
position_dodge_preserve |
Passed to
|
fill_mode |
A character string controlling fill colour mapping:
|
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
symnum_args |
A list of arguments passed to
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
add_point |
Logical; add jittered or beeswarm points to the plot. |
pt_color |
Colour of the points. When |
pt_size |
Numeric size of the points. Default computed from
data size: |
pt_alpha |
Numeric transparency of the points. |
y_nbreaks |
Integer number of y-axis breaks. |
jitter_width |
Numeric width of the jitter. Defaults to
|
jitter_height |
Numeric height of the jitter. Default |
stack |
Logical; stack facetted panels in a compact layout with shared strip labels. |
y_max, y_min |
Numeric y-axis limits, or quantile notation strings
(e.g., |
y_trans |
A character string for y-axis transformation
(e.g., |
y_brackets |
Numeric y-axis position for significance brackets (or p-value labels for multiple comparisons). If NULL, the brackets are placed above the maximum y-value. |
add_beeswarm |
Logical; use |
beeswarm_method |
Beeswarm layout method: |
beeswarm_cex |
Numeric scaling for point spacing. Larger values spread points more. |
beeswarm_priority |
Point layout priority: |
beeswarm_dodge |
Numeric dodge width for beeswarm points when
|
add_box |
Logical; overlay a box plot on the primary geometry.
Mutually exclusive with |
box_color |
Colour of the overlaid box plot outline and fill. |
box_width |
Width of the overlaid box plot. |
box_ptsize |
Size of the median point in the overlaid box plot. |
add_errorbar |
Type of error bars for bar plots ( |
errorbar_color |
Colour of the error bar lines and caps. |
errorbar_width |
Width of the error bar caps. |
errorbar_linewidth |
Line width of the error bars. |
add_trend |
Logical; add trend lines connecting group medians. |
trend_color |
Colour of the trend line. When |
trend_linewidth |
Width of the trend line. |
trend_ptsize |
Size of the trend line points. |
add_stat |
A summary function (e.g., |
stat_name |
Legend title for the stat summary shape. |
stat_color |
Colour of the stat summary point. |
stat_size |
Size of the stat summary point. |
stat_stroke |
Stroke width of the stat summary point. |
stat_shape |
Shape (an integer) for the stat summary point. Uses
|
add_bg |
Logical; add alternating background stripes. |
bg_palette |
Palette for the background stripes. |
bg_palcolor |
Custom colours for the background stripes. |
bg_alpha |
Alpha transparency for the background stripes. |
add_line |
A numeric y-intercept for a horizontal reference line. |
line_color |
Colour of the reference line. |
line_width |
Width of the reference line. |
line_type |
Linetype of the reference line. |
highlight |
A specification of points to highlight: |
highlight_color |
Colour of highlighted points. |
highlight_size |
Size of highlighted points. |
highlight_alpha |
Alpha of highlighted points. |
comparisons |
A logical value ( |
ref_group |
A character string specifying the reference group for comparisons. |
pairwise_method |
Method for pairwise tests. Default
|
multiplegroup_comparisons |
Logical; perform an omnibus test (e.g., Kruskal-Wallis) across all groups. |
multiple_method |
Method for the omnibus test. Default
|
sig_label |
Label format for significance annotations. For
pairwise comparisons: |
sig_labelsize |
Size of the significance label text. |
hide_ns |
Logical; hide non-significant comparison labels. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object, possibly faceted, with height
and width attributes (in inches) attached.
Architecture
-
Wide-to-long conversion — when
in_form = "wide", data is pivoted viatidyr::pivot_longer(). Thekeep_na/keep_emptylists are filtered to the new column names. -
Column resolution —
x,y,group_by,facet_by, andpaired_byare validated viacheck_columns. -
NA / empty-level handling — per-column
keep_emptysettings are extracted forx,group_by, andfacet_byindependently. -
Beeswarm validation — if
add_beeswarm = TRUE, theggbeeswarmpackage is required. Beeswarm is disabled (with a warning) whenpaired_byis provided. -
Paired data validation — structural checks ensure each (
x,paired_by) combination has exactly 2 observations (one per group whengroup_byis present). Paired observations forceadd_point = TRUE. -
Summary statistics —
.y_meanand.y_medianare pre-computed per (x,group_by,facet_by) for use in trend lines and fill modes. -
y-axis limits —
y_max/y_minaccept numeric values or quantile notation ("q95","q5"). For bar plots, the limit is extended upward by the error bar extent. -
Highlight —
highlightcan beTRUE(all points), a numeric index vector, a logical expression string, or a character vector of row names. -
sort_x — an R expression string (e.g.,
"mean(y)") evaluated per x-level to reorder categories. -
Flip transformation — when
flip = TRUE, factor levels are reversed andaspect.ratiois inverted. -
Base geometry — the primary geom is added:
geom_boxplot(),geom_violin(), orstat_summary(fun = mean, geom = "col"). Error bars (SEM / SD / CI) are layered on bar plots via a customstat_summary(fun.data = ...). -
Fill mode —
fill_modecontrols colour mapping:-
"dodge"— fill bygroup_by(discrete). -
"x"— fill by x-axis categories (discrete). -
"mean"/"median"— fill by pre-computed mean/median (continuous gradient).
-
-
Box overlay — when
add_box = TRUEon a non-box base, a box plot is overlaid viaggnewscale::new_scale_fill()with a white fill/black outline. -
Statistical comparisons — two pathways:
-
Pairwise (
comparisons) — usesggpubr::geom_pwc()with automatic or explicit comparison pairs. Data is preprocessed to avoid test failures from zero-variance or all-NA groups. -
Multiple-group (
multiplegroup_comparisons) — usesggpubr::stat_compare_means()for omnibus tests (e.g., Kruskal-Wallis).
After comparison layers are added,
y_max_useis expanded to accommodate significance brackets. -
-
Points — jittered points (
geom_point()withposition_jitterdodge) or beeswarm points (ggbeeswarm::geom_beeswarm()). Paired observations add connecting lines (geom_line()) between matched subjects. -
Trend lines —
stat_summary(fun = first)draws lines connecting group medians. Whentrend_colorisNULLandgroup_byis present, lines are coloured per group. -
Reference lines —
geom_hline()at the specified y-intercept. -
Stat summary points — a custom
stat_summary()point layer displaying a user-specified summary statistic (e.g., mean) with a shape legend entry. -
Stack layout — when
stack = TRUE, facets are arranged with shared strip labels and negative panel spacing for a compact stacked appearance. -
Dimension calculation —
calculate_plot_dimensions()accounts for the number of x-levels × dodge groups, flip state, and stack layout adjustments. Minimum dimensions are enforced from label character widths. -
Faceting —
facet_plot()wraps the result with the appropriate strip position based on flip/stack state.
Chord / Circos plot
Description
Draws a chord diagram (also known as a circos plot) to visualise relationships between two categorical variables. Categories are arranged around a circle, and connecting ribbons (links) represent the flow or association between source and target nodes. The width of each link is proportional to the associated numeric value or observation count.
The function supports count aggregation (omit y to plot
observation counts per pair), link colouring by source or target
node, label rotation options, and splitting into separate
sub-diagrams via split_by.
CircosPlot is an alias of ChordPlot.
CircosPlot is an alias for ChordPlot.
Usage
ChordPlot(
data,
y = NULL,
from = NULL,
from_sep = "_",
to = NULL,
to_sep = "_",
split_by = NULL,
split_by_sep = "_",
flip = FALSE,
links_color = c("from", "to"),
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 0.5,
labels_rot = FALSE,
title = NULL,
subtitle = NULL,
seed = 8525,
keep_na = FALSE,
keep_empty = FALSE,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
CircosPlot(
data,
y = NULL,
from = NULL,
from_sep = "_",
to = NULL,
to_sep = "_",
split_by = NULL,
split_by_sep = "_",
flip = FALSE,
links_color = c("from", "to"),
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 0.5,
labels_rot = FALSE,
title = NULL,
subtitle = NULL,
seed = 8525,
keep_na = FALSE,
keep_empty = FALSE,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
from |
A character string (or vector) specifying the column name(s)
for the source nodes. Character/factor columns are expected. Multiple
columns are concatenated with |
from_sep |
A character string to join multiple |
to |
A character string (or vector) specifying the column name(s)
for the target nodes. Character/factor columns are expected. Multiple
columns are concatenated with |
to_sep |
A character string to join multiple |
split_by |
The column(s) to split the data by for separate sub-diagrams.
Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
flip |
Logical; if |
links_color |
A character string controlling which node's colour
each link ribbon takes: |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
labels_rot |
Logical; if |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
seed |
A numeric seed for reproducibility. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout. |
byrow |
Logical; fill the combined layout by row (default |
axes, axis_titles |
Character strings for axis handling in the combined layout. |
guides |
Character string for legend collection across panels. |
design |
A custom layout design for the combined plot. |
... |
Additional arguments. |
Value
A patchwork object or a named list of wrapped elements
(when combine = FALSE), each with height and width
attributes in inches.
split_by workflow
When split_by is provided:
-
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments for all columns (split_by,from,to). The
split_bycolumn is validated and its NA / empty levels are processed. It is then removed from the per-column lists.The data is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
paletteandpalcolorare resolved viacheck_palette()andcheck_palcolor().-
ChordPlotAtomic()is called for each split. Whentitleis a function, it receives the split level name for dynamic titles. Results are combined via
combine_plots().
Examples
set.seed(8525)
data <- data.frame(
nodes1 = sample(c("Soure1", "Source2", "Source3"), 10, replace = TRUE),
nodes2 = sample(letters[1:3], 10, replace = TRUE),
y = sample(1:5, 10, replace = TRUE)
)
# Basic chord diagram (counts)
ChordPlot(data, from = "nodes1", to = "nodes2")
# Links coloured by target + rotated labels
ChordPlot(data, from = "nodes1", to = "nodes2",
links_color = "to", labels_rot = TRUE)
# With explicit y values (link thickness)
ChordPlot(data, from = "nodes1", to = "nodes2", y = "y")
# Split by a column — one diagram per split level
ChordPlot(data, from = "nodes1", to = "nodes2", split_by = "y")
# Per-split palettes
ChordPlot(data, from = "nodes1", to = "nodes2", split_by = "y",
palette = c("1" = "Reds", "2" = "Blues",
"3" = "Greens", "4" = "Purp"))
# Flip source/target direction
ChordPlot(data, from = "nodes1", to = "nodes2", flip = TRUE)
Atomic chord plot (internal)
Description
Core implementation for drawing a chord diagram using
circlize::chordDiagram(). This is the workhorse behind the
exported ChordPlot function — it takes a single data
frame (no split_by support) and returns a patchwork
wrapped element.
Chord diagrams visualise relationships (flows) between two sets of
categories arranged around a circle. The width of each link is
proportional to the value (y) connecting its source and target
nodes.
Usage
ChordPlotAtomic(
data,
y = NULL,
from = NULL,
from_sep = "_",
to = NULL,
to_sep = "_",
flip = FALSE,
links_color = c("from", "to"),
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 0.5,
labels_rot = FALSE,
title = NULL,
subtitle = NULL,
keep_na = FALSE,
keep_empty = FALSE,
...
)
Arguments
data |
A data frame. |
y |
A character string specifying the numeric column whose values
determine link thickness. When |
from |
A character string (or vector) specifying the column name(s)
for the source nodes. Character/factor columns are expected. Multiple
columns are concatenated with |
from_sep |
A character string to join multiple |
to |
A character string (or vector) specifying the column name(s)
for the target nodes. Character/factor columns are expected. Multiple
columns are concatenated with |
to_sep |
A character string to join multiple |
flip |
Logical; if |
links_color |
A character string controlling which node's colour
each link ribbon takes: |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
Numeric transparency for the link ribbons (0–1).
Default |
labels_rot |
Logical; if |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
... |
Additional arguments. |
Value
A patchwork wrapped element with height and
width attributes (in inches) attached. The original data is
stored in the p$data field.
Architecture
-
Column resolution —
from,to, andyare validated and transformed viacheck_columns. Multi-columnfromandtoare concatenated with their respective separators (from_sep,to_sep). -
Count aggregation — when
y = NULL, the count of observations per (from,to) pair is computed as a new.ycolumn. Factor levels from the original data are preserved. -
NA / empty-level handling —
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. -
Flip — when
flip = TRUE, thefromandtocolumns are swapped, effectively reversing the link direction. -
Colour mapping —
palette_this()assigns colours to all uniquefromandtovalues (the grid sectors).NAvalues are mapped to a literal"NA"level and assigned a colour from the palette. -
Link colour resolution —
links_colorcontrols whether each connecting ribbon takes its colour from the"from"side (default) or the"to"side. -
circlize rendering — two rendering paths exist, selected by
labels_rot:-
Horizontal labels (
labels_rot = FALSE): track 1 has a fixed height of 1 mm and usesniceFacing = TRUEfor automatic label rotation. Track 2 adds axis ticks on the outside for wide-enough sectors. -
Rotated labels (
labels_rot = TRUE): track 1 height is computed from the maximum string width of all node names, and labels are rendered withfacing = "clockwise". Track 2 adds axis ticks.
Links use arrow heads (
link.arr.type = "big.arrow") and differentiated height (direction.type = c("diffHeight", "arrows")). Both tracks setbg.border = NAto prevent border lines from appearing between sectors. -
-
Patchwork integration — the circlize formula is wrapped via
wrap_elements()so it can be composed with other ggplot objects. Title and subtitle are added viaplot_annotation(). -
Dimension attributes —
heightandwidthattributes (in inches) are set to a base size (7) scaled up by 2, 4, or 6 depending on the maximum label character width whenlabels_rot = TRUE.
Clustree Plot
Description
Creates a clustree (clustering tree) plot visualising how cluster assignments change across increasing clustering resolutions. The plot helps identify stable clustering solutions and understand the hierarchical relationships among clusters at different resolution thresholds.
The function expects a data frame with columns named by a common
prefix followed by numeric resolution values (e.g.
"res_0.1", "res_0.3", "res_0.5"). Each column
contains cluster labels (factor or character) for every observation at
that resolution.
Internally, the function uses clustree::clustree() to compute a
ggraph-based tree layout where nodes are clusters and edges
represent cells transitioning between clusters at adjacent resolutions.
Edge colour and width encode the number of transitioning cells.
Key features:
-
Resolution-level node colouring — each resolution receives a distinct colour from the selected
palette. -
Edge gradient — edges are coloured by transition count using a separate
edge_palettecolour gradient. -
Flip support —
flip = TRUEplaces resolutions on the x-axis for left-to-right reading. -
Split by groups —
split_bygenerates per-group clustree plots that are combined viapatchwork. -
Automatic dimensions — plot height and width are automatically computed based on the number of resolutions, clusters, and the legend configuration.
Usage
ClustreePlot(
data,
prefix,
flip = FALSE,
split_by = NULL,
split_by_sep = "_",
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
edge_palette = "Spectral",
edge_palcolor = NULL,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
expand = c(0.1, 0.1),
theme = "theme_this",
theme_args = list(),
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
prefix |
A character string specifying the common prefix of the
resolution columns in |
flip |
A logical value. If |
split_by |
The column(s) to split data by and generate separate
clustree plots for each level. Each split level produces an independent
clustree plot via |
split_by_sep |
A character string used to concatenate multiple
|
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
edge_palette |
A character string specifying the palette name for
the edge colour gradient. Edges are coloured by the number of
transitioning cells between clusters at adjacent resolutions, using
|
edge_palcolor |
A character vector of custom colours for the edge
colour gradient. When |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
combine |
A logical value. If |
nrow, ncol, byrow |
Integers controlling the layout of combined plots
via |
seed |
The random seed for reproducibility. Passed to
|
axes, axis_titles |
Strings controlling how axes and axis titles are
handled across combined plots. Passed to |
guides |
A string controlling guide collection across combined
plots. Passed to |
design |
A custom layout specification for combined plots. Passed
to |
... |
Additional arguments passed to |
Value
A ggplot object (single plot), a patchwork object
(when combine = TRUE with split_by), or a list of
ggplot objects (when combine = FALSE).
split_by Workflow (ClustreePlot)
When split_by is provided, the following pipeline executes:
-
Argument validation —
validate_common_args()checks theseedvalue and sets the random seed. -
Theme resolution —
process_theme()resolves thethemestring or function to a theme function. -
Split column validation —
check_columns()resolvessplit_bywithforce_factor = TRUE, allow_multi = TRUE, concat_multi = TRUE. -
Data splitting — splits
databysplit_bylevels (unused levels dropped), preserving factor level order. -
Per-split palette / colour / legend —
check_palette(),check_palcolor(), andcheck_legend()resolve per-split overrides forpalette,palcolor,legend.position, andlegend.direction. -
Per-split title — when
titleis a function, it receives the default title (the split level name) and can return a custom string; otherwisetitle %||% split_levelis used. -
Dispatch — each split subset is passed to
ClustreePlotAtomicwith the per-split parameters. -
Combination —
combine_plots()assembles the list of plots viapatchwork::wrap_plots, honouringnrow/ncol/byrow/design.
Examples
set.seed(8525)
N <- 100
data <- data.frame(
p.0.4 = sample(LETTERS[1:5], N, replace = TRUE),
p.0.5 = sample(LETTERS[1:6], N, replace = TRUE),
p.0.6 = sample(LETTERS[1:7], N, replace = TRUE),
p.0.7 = sample(LETTERS[1:8], N, replace = TRUE),
p.0.8 = sample(LETTERS[1:9], N, replace = TRUE),
p.0.9 = sample(LETTERS[1:10], N, replace = TRUE),
p.1 = sample(LETTERS[1:30], N, replace = TRUE),
split = sample(1:2, N, replace = TRUE)
)
# --- Basic clustree plot ---
ClustreePlot(data, prefix = "p")
# --- Flipped layout (resolutions on x-axis) ---
ClustreePlot(data, prefix = "p", flip = TRUE)
# --- Split by group ---
ClustreePlot(data, prefix = "p", split_by = "split")
# --- Split by group with per-split palettes ---
ClustreePlot(data, prefix = "p", split_by = "split",
palette = c("1" = "Set1", "2" = "Paired"))
Atomic clustree plot
Description
Core implementation for clustree (clustering tree) plots. This internal
function renders a tree-based visualisation showing how cluster assignments
change across increasing clustering resolutions. It is called by the
exported ClustreePlot() function.
Usage
ClustreePlotAtomic(
data,
prefix,
flip = FALSE,
alpha = 0.85,
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
edge_palette = "Spectral",
edge_palcolor = NULL,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
expand = c(0.1, 0.1),
theme = "theme_this",
theme_args = list(),
...
)
Arguments
data |
A data frame. |
prefix |
A character string specifying the common prefix of the
resolution columns in |
flip |
A logical value. If |
alpha |
A numeric value in |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
edge_palette |
A character string specifying the palette name for
the edge colour gradient. Edges are coloured by the number of
transitioning cells between clusters at adjacent resolutions, using
|
edge_palcolor |
A character vector of custom colours for the edge
colour gradient. When |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
... |
Additional arguments passed to |
Details
The function expects a data frame containing columns named with a common
prefix followed by numeric resolution values (e.g. "res_0.1",
"res_0.3", "res_0.5"). Each column represents cluster
assignments at a given resolution, and the tree visualises how cells (rows)
transition between clusters as resolution increases.
The core layout is produced via clustree::clustree(), which computes
a ggraph layout (default: "sugiyama") linking clusters across
adjacent resolutions. Nodes represent clusters and edges represent cell
transitions; edge width and colour encode the number of transitioning cells.
Cluster labels are overlaid on each node via ggplot2::geom_text().
Key features:
-
Resolution-level node colouring — each resolution level receives a distinct colour from
paletteviaggplot2::scale_color_manual(). -
Edge gradient — edges are coloured by transition count using
ggraph::scale_edge_color_gradientn()with theedge_palettegradient. -
Flip support —
flip = TRUEplaces resolutions on the x-axis with cluster IDs as y-axis row labels for left-to-right reading. -
Automatic dimension calculation — plot height and width are sized based on the number of resolutions, number of clusters, and legend configuration, with different formulae for flipped vs. non-flipped layouts.
Value
A ggplot object with height and width
attributes.
Architecture
ClustreePlotAtomic executes the following steps:
-
Column selection — selects all columns whose names start with
prefixviadplyr::starts_with(). -
NA filtering — removes rows with any missing values via
stats::complete.cases(). -
Expansion normalisation —
norm_expansion()parses theexpandargument for continuous x and y axes. -
Empty data guard — stops with an informative error if no columns match the prefix or no complete rows remain.
-
Resolution parsing — extracts the suffix after
prefixfrom each column name and strips leading separators ("_"or".") if present. Values are converted to numeric and sorted. Column names are rewritten to use the original prefix for consistentclustreeprocessing. -
Cluster counting — computes the number of unique clusters at the highest resolution (
max_clusters), used for dimension calculation in the non-flipped layout. -
Argument merging — builds a call to
clustree::clustree()by merging user-supplied...with sensible defaults fornode_alpha,edge_width,show_axis,layout("sugiyama"),node_size_range(c(6, 12)),node_text_size(3), andnode_text_colour("black"). -
clustree execution — calls
gglogger::register(clustree::clustree)with the merged arguments to produce the baseggplotobject. -
Node labels — overlays
ggplot2::geom_text()with the cluster label from theclustreeoutput, using the configured text size and colour. -
Resolution colour scale — applies
ggplot2::scale_color_manual()with one colour per resolution level usingpalette_this(). The colour legend is suppressed (the edge gradient legend serves as the primary guide). -
Edge colour scale — applies
ggraph::scale_edge_color_gradientn()with theedge_palettepalette, encoding transition counts via a colour-bar guide with black frame and ticks. -
Theme and labels — applies the selected theme and sets
title,subtitle, x-axis label, and y-axis label (default y-label is theprefixwith trailing separator stripped). -
Flip branch (
flip = TRUE):Resolutions are placed on the x-axis (horizontal); clusters become y-axis rows.
Width scales with
max(3, 0.5 + nres * 1.0); height scales withmax(3, 0.5 + max_clusters * 0.5)(or via aspect.ratio).-
scale_y_reverse()+coord_flip()reorients the layout so resolutions read left-to-right. Horizontal grid lines are dashed grey80; y-axis text and ticks are suppressed.
-
Non-flip branch (
flip = FALSE, default):Resolutions are on the y-axis (rows); clusters spread across the x-axis (columns).
Width scales with
max(3, 0.5 + max_clusters * 0.5); height scales withmax(3, 0.5 + nres * 1.0)(or via aspect.ratio).-
coord_cartesian(clip = "off")andscale_y_continuous()show resolution labels on the y-axis. Vertical grid lines are dashed grey80; x-axis text and ticks are suppressed.
-
Dimension storage —
calculate_plot_dimensions()computesheightandwidthattributes, stored on theggplotobject.
Correlation pairs (scatterplot matrix)
Description
Draws a grid of pairwise scatter plots for selected numeric columns, arranged in a scatterplot matrix layout. The upper or lower triangle displays correlation tiles while the opposite triangle shows scatter plots with regression lines. Diagonal cells can show density plots, violin plots, histograms, box plots, or a simple diagonal line.
NOTE: The facet_by parameter is not supported
in CorPairsPlot (an error is raised if provided). Use
split_by instead to create separate correlation pair matrices
per group.
The function supports four layout orientations (layout),
three correlation methods, configurable diagonal plots via
other plotthis functions, custom correlation tile formatting, and
splitting into separate sub-plots via split_by.
Usage
CorPairsPlot(
data,
columns = NULL,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
split_by = NULL,
split_by_sep = "_",
diag_type = NULL,
diag_args = list(),
layout = c(".\\", "\\.", "/.", "./"),
cor_method = c("pearson", "spearman", "kendall"),
cor_palette = "RdBu",
cor_palcolor = NULL,
cor_size = 3,
cor_format = "corr: {round(corr, 2)}",
cor_fg = "black",
cor_bg = "white",
cor_bg_r = 0.1,
theme = "theme_this",
theme_args = list(),
palette = ifelse(is.null(group_by), "Spectral", "Paired"),
palcolor = NULL,
palreverse = FALSE,
title = NULL,
subtitle = NULL,
facet_by = NULL,
legend.position = "right",
legend.direction = "vertical",
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
columns |
A character vector of column names to include in the
pairs plot. When |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string used as the colour legend title
in the scatter plots. When |
split_by |
The column(s) to split the data by and produce separate
sub-plots. Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
diag_type |
A character string specifying the plot type for
diagonal cells. One of |
diag_args |
A named list of additional arguments passed to the
diagonal plot function ( |
layout |
A character string specifying the layout orientation.
One of the following codes (dot = scatter, backslash/slash =
diagonal): |
cor_method |
A character string specifying the correlation method
for the fill tiles. One of |
cor_palette |
A character string specifying the colour palette for
the correlation fill tiles. Default: |
cor_palcolor |
A character vector of custom colours used to create
the correlation tile palette. When |
cor_size |
A numeric value specifying the font size of the
correlation text in the fill tiles. Default: |
cor_format |
A character string specifying a glue template for
formatting the correlation text. The template is evaluated by
|
cor_fg |
A character string specifying the colour of the
correlation text. Default: |
cor_bg |
A character string specifying the background colour of
the correlation text boxes. Default: |
cor_bg_r |
A numeric value specifying the corner radius of the
correlation text background boxes. Default: |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
seed |
A numeric seed for reproducibility. |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout. |
byrow |
Logical; fill the combined layout by row. Default
|
axes |
A character string specifying how axes should be treated across the combined layout. |
axis_titles |
A character string specifying how axis titles should
be treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should be collected across panels. |
design |
A custom layout design for the combined plot. |
... |
Additional arguments. |
Value
A patchwork object (when combine = TRUE) or a
named list of patchwork objects (when combine = FALSE),
each with height and width attributes in inches.
split_by workflow
When split_by is provided:
The
split_bycolumn is validated viacheck_columns()withforce_factor = TRUE. Empty levels are dropped.The data frame is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...". Thesplit_bycolumn is removed from each split's data before plotting.Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
CorPairsPlotAtomic()is called for each split. Whentitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
set.seed(8525)
data <- data.frame(x = rnorm(100))
data$y <- rnorm(100, 10, sd = 0.5)
data$z <- -data$x + data$y + rnorm(100, 20, 1)
data$g <- sample(1:4, 100, replace = TRUE)
# Histogram diagonal, slash layout
CorPairsPlot(data, diag_type = "histogram",
diag_args = list(bins = 30, palette = "Paired"),
layout = "/.")
# No diagonal with axis title styling
CorPairsPlot(data, group_by = "g", diag_type = "none", layout = "./",
theme_args = list(axis.title = element_textbox(
color = "black", box.color = "grey20", size = 16, halign = 0.5,
fill = "grey90", linetype = 1,
width = grid::unit(1, "npc"),
padding = ggplot2::margin(5, 5, 5, 5))))
# Violin diagonal with custom format
CorPairsPlot(data, group_by = "g", diag_type = "violin", layout = "\\.",
cor_format = "{x}\n{y}\ncorr: {round(corr, 2)}")
# Per-split with bottom legend
CorPairsPlot(data, split_by = "g", diag_type = "none", layout = ".\\",
legend.position = "bottom", legend.direction = "horizontal",
group_name = "group")
# Per-split with custom palette colours
CorPairsPlot(data, split_by = "g",
palcolor = list("1" = "red", "2" = "blue", "3" = "green",
"4" = "yellow"))
Atomic Correlation Pairs Plot
Description
Core implementation for drawing a correlation pairs (scatterplot matrix)
grid. This is the workhorse behind the exported
CorPairsPlot — it takes a single data frame (no
split_by support) and returns a patchwork object.
The grid arranges all pairwise scatter plots of selected columns. The upper or lower triangle displays correlation tiles (fill) while the opposite triangle displays scatter plots with regression lines. The diagonal can show density plots, violin plots, histograms, box plots, or a simple diagonal line.
The function supports four layout orientations (layout),
three correlation methods (cor_method), configurable
diagonal plots using other plotthis functions, and custom correlation
tile formatting.
Usage
CorPairsPlotAtomic(
data,
columns = NULL,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
diag_type = NULL,
diag_args = list(),
layout = c(".\\", "\\.", "/.", "./"),
cor_method = c("pearson", "spearman", "kendall"),
cor_palette = "RdBu",
cor_palcolor = NULL,
cor_size = 3,
cor_format = "corr: {round(corr, 2)}",
cor_fg = "black",
cor_bg = "white",
cor_bg_r = 0.1,
theme = "theme_this",
theme_args = list(),
palette = ifelse(is.null(group_by), "Spectral", "Paired"),
palcolor = NULL,
palreverse = FALSE,
title = NULL,
subtitle = NULL,
facet_by = NULL,
legend.position = "right",
legend.direction = "vertical",
seed = 8525,
...
)
Arguments
data |
A data frame. |
columns |
A character vector of column names to include in the
pairs plot. When |
group_by |
A character vector of column names to colour the
scatter points by. Each unique combination becomes a separate group.
Required for |
group_by_sep |
A character string to separate concatenated
|
group_name |
A character string used as the colour legend title
in the scatter plots. When |
diag_type |
A character string specifying the plot type for
diagonal cells. One of |
diag_args |
A named list of additional arguments passed to the
diagonal plot function ( |
layout |
A character string specifying the layout orientation.
One of the following codes (dot = scatter, backslash/slash =
diagonal): |
cor_method |
A character string specifying the correlation method
for the fill tiles. One of |
cor_palette |
A character string specifying the colour palette for
the correlation fill tiles. Default: |
cor_palcolor |
A character vector of custom colours used to create
the correlation tile palette. When |
cor_size |
A numeric value specifying the font size of the
correlation text in the fill tiles. Default: |
cor_format |
A character string specifying a glue template for
formatting the correlation text. The template is evaluated by
|
cor_fg |
A character string specifying the colour of the
correlation text. Default: |
cor_bg |
A character string specifying the background colour of
the correlation text boxes. Default: |
cor_bg_r |
A numeric value specifying the corner radius of the
correlation text background boxes. Default: |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments passed to the underlying
|
Details
theme and theme_args are supported and passed to
each individual cell plot.
Value
A patchwork object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
facet_by guard — raises an error if
facet_byis provided (not supported in pairs plots; usesplit_byinstead). -
Column resolution — when
columnsisNULL, all columns (exceptgroup_by) are used. Otherwise,columnsare validated viacheck_columns(). At least two columns are required. -
Default diag_type — when
diag_typeisNULL, it defaults to"density"(nogroup_by) or"violin"(withgroup_by). -
Layout determination —
get_plot_info()is called for each cell(i, j)to determine:-
Type:
layout(diagonal line),"cor"(scatter plot with regression),"fill"(correlation tile). -
Axis/label positions: which sides of the cell should show x-axis, y-axis, x-label, and y-label, based on the cell's location in the matrix and the chosen layout.
-
-
Cell rendering —
get_plot()draws each cell based on itsinfo$type:-
Diagonal,
diag_type = "none"— draws an X or backslash diagonal line viageom_line(). -
Diagonal,
"density"— delegates toDensityPlot(). -
Diagonal,
"violin"— delegates toViolinPlot(); requiresgroup_by. -
Diagonal,
"histogram"— delegates toHistogram(). -
Diagonal,
"box"— delegates toBoxPlot(); requiresgroup_by. -
Off-diagonal,
"cor"— delegates toCorPlot()for the scatter plot with regression line. -
Off-diagonal,
"fill"— draws ageom_tile()filled by the correlation value withscale_fill_gradientn()and displays the formatted correlation viaggrepel::geom_text_repel().
-
-
Axis/label positioning — axes, axis titles, and labels are positioned at the margins of the full grid based on
info$xaxis,info$yaxis,info$xlab,info$ylabusingscale_x_*/scale_y_*with appropriatepositionarguments. -
Layout assembly — all cell plots are arranged into a matrix via
patchwork::wrap_plots()withncol = length(columns). Guides are collected, and the title/subtitle are added viaplot_annotation(). The result is wrapped inpatchwork::wrap_elements()so the title displays correctly. -
Dimension calculation —
calculate_plot_dimensions()computesheightandwidthattributes frombase_height = sqrt(length(columns)) * 4, a fixed aspect ratio of 1, and legend metrics.
Correlation scatter plot
Description
Draws a scatter plot of two numeric variables with a linear regression
line, optional correlation statistics, and point highlighting. This is
the public entry point that wraps CorPlotAtomic with
split_by support.
Key features include group-based colouring (group_by),
point highlighting by expression, rowname, or index,
annotation items (regression equation, R-squared, p-value,
Spearman/Pearson/Kendall rho, N), raster rendering for large
datasets, faceting (facet_by), and splitting
into separate sub-plots via split_by.
Usage
CorPlot(
data,
x,
y,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
split_by = NULL,
split_by_sep = "_",
pt_size = 2,
pt_shape = 16,
raster = FALSE,
alpha = 1,
raster_dpi = c(512, 512),
highlight = NULL,
highlight_color = "black",
highlight_size = 1,
highlight_alpha = 1,
highlight_stroke = 0.8,
anno_items = c("eq", "r2", "p"),
anno_size = 3,
anno_fg = "black",
anno_bg = "white",
anno_bg_r = 0.1,
anno_position = c("topleft", "topright", "bottomleft", "bottomright", "tl", "tr", "bl",
"br"),
add_smooth = TRUE,
smooth_color = "red2",
smooth_width = 1.5,
smooth_se = FALSE,
theme = "theme_this",
theme_args = list(),
palette = ifelse(is.null(group_by), "Spectral", "Paired"),
palcolor = NULL,
palreverse = FALSE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string used as the colour legend title.
When |
split_by |
The column(s) to split the data by and produce separate
sub-plots. Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
pt_size |
A numeric value specifying the size of the points.
Default: |
pt_shape |
A numeric value specifying the shape of the points
(see |
raster |
A logical value. When |
alpha |
A numeric value specifying the transparency of the plot. |
raster_dpi |
An integer vector of length 1 or 2 specifying the
raster resolution in (width, height) pixels. When a single value is
provided, it is recycled. Default: |
highlight |
Specifies which points to emphasise. Can be:
Default: |
highlight_color |
A character string specifying the colour of the
highlighted point borders. Default: |
highlight_size |
A numeric value specifying the size of the
highlighted points (the inner fill). Default: |
highlight_alpha |
A numeric value specifying the alpha transparency
of the highlighted points. Default: |
highlight_stroke |
A numeric value specifying the stroke width of
the highlighted point borders. The outer layer size is
|
anno_items |
A character vector specifying which statistics to
display as text annotation. Available items: |
anno_size |
A numeric value specifying the font size of the
annotation text (scaled by |
anno_fg |
A character string specifying the colour of the
annotation text. Default: |
anno_bg |
A character string specifying the background colour of
the annotation text boxes. Default: |
anno_bg_r |
A numeric value specifying the corner radius of the
annotation text background boxes. Default: |
anno_position |
A character string specifying the corner position
of the annotation text. One of |
add_smooth |
A logical value. When |
smooth_color |
A character string specifying the colour of the
regression line. Default: |
smooth_width |
A numeric value specifying the linewidth of the
regression line. Default: |
smooth_se |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
seed |
A numeric seed for reproducibility. Passed to
|
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined
layout (passed to |
byrow |
Logical; fill the combined layout by row. Default
|
axes |
A character string specifying how axes should be treated
across the combined layout (passed to
|
axis_titles |
A character string specifying how axis titles should
be treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should
be collected across panels (passed to |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments. |
Value
A ggplot object (when split_by is NULL),
a patchwork object (when combine = TRUE), or a named
list of ggplot objects (when combine = FALSE), each
with height and width attributes in inches.
split_by workflow
When split_by is provided:
The
split_bycolumn is validated viacheck_columns()withforce_factor = TRUE. Empty levels are dropped (droplevels()).The data frame is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
CorPlotAtomic()is called for each split. Whentitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
data(iris)
# Basic scatter with group colours
CorPlot(iris, "Sepal.Length", "Sepal.Width", group_by = "Species")
# Highlight a specific group with custom stroke
CorPlot(iris, "Sepal.Length", "Sepal.Width", group_by = "Species",
highlight = 'Species == "setosa"', highlight_stroke = 1.5,
anno_items = c("eq", "pearson"), anno_position = "bottomright")
# Faceted by species
CorPlot(iris, "Sepal.Length", "Sepal.Width", facet_by = "Species",
facet_scales = "free")
# Per-split palettes
CorPlot(iris, "Sepal.Length", "Sepal.Width", split_by = "Species",
palette = c(setosa = "Set1", versicolor = "Dark2", virginica = "Paired"))
Atomic Correlation Plot
Description
Core implementation for drawing a scatter plot of two variables with a
linear regression line, optional correlation statistics, and point
highlighting. This is the workhorse behind the exported
CorPlot — it takes a single data frame (no
split_by support) and returns a ggplot object with
faceting applied.
The function supports group-based colouring (group_by),
point highlighting by expression or rowname, multiple annotation items
(regression equation, R-squared, p-value, Spearman/Pearson/Kendall
correlation, N), raster rendering for large datasets, configurable
regression line style, and faceting.
Usage
CorPlotAtomic(
data,
x,
y,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
pt_size = 2,
pt_shape = 16,
alpha = 1,
raster = FALSE,
raster_dpi = c(512, 512),
highlight = NULL,
highlight_color = "black",
highlight_size = 1,
highlight_alpha = 1,
highlight_stroke = 0.8,
anno_items = c("eq", "r2", "p"),
anno_size = 3,
anno_fg = "black",
anno_bg = "white",
anno_bg_r = 0.1,
anno_position = c("topleft", "topright", "bottomleft", "bottomright", "tl", "tr", "bl",
"br"),
add_smooth = TRUE,
smooth_color = "red2",
smooth_width = 1.5,
smooth_se = FALSE,
theme = "theme_this",
theme_args = list(),
palette = ifelse(is.null(group_by), "Spectral", "Paired"),
palcolor = NULL,
palreverse = FALSE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
seed = 8525,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name for the x-axis. Must be numeric. |
y |
A character string specifying the column name for the y-axis. Must be numeric. |
group_by |
A character vector of column names to colour the points
by. Each unique combination becomes a separate group in the legend.
Multiple columns are concatenated with |
group_by_sep |
A character string to separate concatenated
|
group_name |
A character string used as the colour legend title.
When |
pt_size |
A numeric value specifying the size of the points.
Default: |
pt_shape |
A numeric value specifying the shape of the points
(see |
alpha |
A numeric value specifying the transparency of the plot. |
raster |
A logical value. When |
raster_dpi |
An integer vector of length 1 or 2 specifying the
raster resolution in (width, height) pixels. When a single value is
provided, it is recycled. Default: |
highlight |
Specifies which points to emphasise. Can be:
Default: |
highlight_color |
A character string specifying the colour of the
highlighted point borders. Default: |
highlight_size |
A numeric value specifying the size of the
highlighted points (the inner fill). Default: |
highlight_alpha |
A numeric value specifying the alpha transparency
of the highlighted points. Default: |
highlight_stroke |
A numeric value specifying the stroke width of
the highlighted point borders. The outer layer size is
|
anno_items |
A character vector specifying which statistics to
display as text annotation. Available items: |
anno_size |
A numeric value specifying the font size of the
annotation text (scaled by |
anno_fg |
A character string specifying the colour of the
annotation text. Default: |
anno_bg |
A character string specifying the background colour of
the annotation text boxes. Default: |
anno_bg_r |
A numeric value specifying the corner radius of the
annotation text background boxes. Default: |
anno_position |
A character string specifying the corner position
of the annotation text. One of |
add_smooth |
A logical value. When |
smooth_color |
A character string specifying the colour of the
regression line. Default: |
smooth_width |
A numeric value specifying the linewidth of the
regression line. Default: |
smooth_se |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Parameter normalisation —
match.arg()resolvesanno_positionabbreviations ("tl","tr","bl","br") to their full forms.raster_dpiis expanded to length 2 when given as a scalar. -
Column resolution —
x,y, andgroup_byare validated viacheck_columns. Multi-columngroup_byis concatenated withgroup_by_sep. -
Grouping fallback — when
group_by = NULL, a dummy.groupcolumn is created and the legend is suppressed (legend.position = "none"). -
Annotation data calculation — the data is grouped by
facet_byand a linear model (lm(y ~ x)) is fitted per group. Each requestedanno_itemsis computed:-
"eq"— regression equationy = a + bx. -
"r2"— R-squared of the model. -
"p"— p-value of the x coefficient. -
"spearman"— Spearman's rho. -
"pearson"— Pearson's r. -
"kendall"— Kendall's tau. -
"n"— number of observations.
The results are stored in an
annodatadata frame forgeom_text_repel. -
-
Highlight parsing — the
highlightargument is resolved into a.highlightlogical column:-
TRUE— highlights all points. A character expression — evaluated via
dplyr::filterto select rows.A character vector — matched against rownames of the data.
A numeric vector — treated as row indices.
-
-
Point rendering — two branches:
-
Raster mode (
raster = TRUE) — usesscattermore::geom_scattermore()for efficient rendering of large datasets. Highlighted points are drawn in two layers (stroke + fill). -
Vector mode (
raster = FALSE, default) — usesggplot2::geom_point()with configurable size, shape, and alpha. Highlighted points get an outer stroke via a second point layer.
-
-
Regression line —
geom_smooth(method = "lm")draws the linear regression line with optional standard error band (smooth_se). -
Annotation text —
ggrepel::geom_text_repel()places the computed annotations at the specifiedanno_positioncorner, with background styling. -
Colour scale —
scale_color_manual()maps group levels to colours viapalette_this(). -
Labels and theme —
labs()sets titles and axis labels. The theme is applied viado_call(), withaspect.ratio,legend.position, andlegend.directionenforced. -
Dimension calculation —
calculate_plot_dimensions()computesheightandwidthattributes frombase_height = 4.5,aspect.ratio, legend metrics, and the number of group levels. -
Faceting —
facet_plot()appliesfacet_wrap/facet_gridiffacet_byis provided.
Atomic density/histogram plot
Description
Core implementation for density and histogram plots. This is the internal workhorse
dispatched by both the DensityPlot() and Histogram() public wrappers. It
renders a grouped density curve or histogram, with optional data-distribution
bars along the y=0 axis, trend-line interpolation (histogram only), and full
faceting support.
The function supports two plotting modes selected by type:
-
density — renders
ggplot2::geom_density()for each group. -
histogram — renders
ggplot2::geom_histogram()with optional trend overlays (use_trend,add_trend), including zero-skip interpolation (trend_skip_zero) that useszoo::na.approx()to bridge gaps where a bin has zero observations under a transformed y-axis.
When add_bars = TRUE, a data rug is drawn along the bottom of the plot using
ggplot2::geom_linerange(). Each group's bars are offset vertically so they
stack without overlapping.
Usage
DensityHistoPlotAtomic(
data,
x,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
xtrans = "identity",
ytrans = "identity",
type = c("density", "histogram"),
bins = NULL,
binwidth = NULL,
flip = FALSE,
keep_na = FALSE,
keep_empty = FALSE,
add_bars = FALSE,
bar_height = 0.025,
bar_alpha = 1,
bar_width = 0.1,
position = "identity",
use_trend = FALSE,
add_trend = FALSE,
trend_alpha = 1,
trend_linewidth = 0.8,
trend_pt_size = 1.5,
trend_skip_zero = FALSE,
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 0.5,
theme = "theme_this",
theme_args = list(),
aspect.ratio = 1,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
expand = c(bottom = 0, left = 0, right = 0),
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
legend.position = ifelse(is.null(group_by), "none", "right"),
legend.direction = "vertical",
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name for the x-axis values. A numeric column is expected. |
group_by |
A character string specifying the column(s) to group the data
by. Multiple columns are concatenated with |
group_by_sep |
A character string used to join multiple |
group_name |
A character string used as the legend title for the
|
xtrans |
A character string specifying the transformation applied to
the x-axis. Passed to |
ytrans |
A character string specifying the transformation applied to
the y-axis. Passed to |
type |
A character string specifying the plot type. |
bins |
A numeric value specifying the number of bins for the histogram.
Ignored when |
binwidth |
A numeric value specifying the width of individual bins for
the histogram. Ignored when |
flip |
A logical value. If |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
add_bars |
A logical value. If |
bar_height |
A numeric value specifying the height (in data units,
relative to the maximum y) of the rug bars added by |
bar_alpha |
A numeric value in |
bar_width |
A numeric value passed as the |
position |
A character string specifying the position adjustment for
the bars or density curves. Default: |
use_trend |
A logical value. If |
add_trend |
A logical value. If |
trend_alpha |
A numeric value in |
trend_linewidth |
A numeric value for the thickness of the trend line.
Default: |
trend_pt_size |
A numeric value for the size of the trend points.
Default: |
trend_skip_zero |
A logical value. If |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
... |
Additional arguments. |
Architecture
DensityHistoPlotAtomic executes the following steps:
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Type check —
match.arg(type, c("density", "histogram")). -
Expansion normalization —
norm_expansion()converts theexpandvector into CSS-padding-style x/y components. -
Column resolution —
check_columns()validatesx,group_by(force_factor, allow_multi, concat_multi), andfacet_by. -
Default group — when
group_byisNULL, a synthetic.groupfactor with a single empty-string level is created so the colour-mapping pipeline runs uniformly. -
Histogram bin default — if
type = "histogram"and neitherbinsnorbinwidthis set,bins = 30with a message. -
Add-bars pre-calculation — when
add_bars = TRUE:For density: max y =
max(density(x)$y) * 1.5.For histogram: max y = max bin count from
cut(x, s).Computes
.yminand.ymaxper row, offset bybar_height * max_yfor each group so rugs stack without colliding.
-
NA / empty handling —
process_keep_na_empty()filters data andkeep_emptyvalues are extracted for group and facet dimensions. -
Palette resolution —
palette_this()maps group levels to colours. -
Base ggplot + scales — initialises
ggplot(data, aes(x, fill, color)), then addsscale_fill_manual()/scale_color_manual(). Whenkeep_empty_groupisTRUE,drop = FALSE,breaks, andlimitsare set to preserve empty factor levels. -
Geometry layer:
-
Histogram (no trend):
geom_histogram(alpha, bins, binwidth, position). -
Histogram (use_trend / add_trend): adds
stat_bin(geom = "point")for trend points +stat_bin(geom = "line")for the trend curve. Whentrend_skip_zero = TRUE, anafter_stat()expression sets zero counts toNA, transforms y, applieszoo::na.approx()per..group.., and inverts — producing a continuous trend that interpolates over empty bins. -
Density:
geom_density(alpha, position).
-
-
Add-bars geometry — if
add_bars = TRUE,geom_linerange()draws vertical ticks at the pre-computed.ymin/.ymaxpositions. -
Scales, theme, labels — x/y continuous scales with transforms, theme applied via
do_call(theme, theme_args), and axis / title labels (default y-lab: "Count" for histogram, "Density" for density). -
Flip — optional
coord_flip(). -
Dimension calculation —
calculate_plot_dimensions(base_height = 3.5, aspect.ratio, legend, flip)setsheight/widthattributes. -
Faceting —
facet_plot()appliesfacet_grid/facet_wrap.
Density Plot / Histogram
Description
Density plot for visualising the distribution of a numeric variable. Uses
ggplot2::geom_density() to render smooth kernel density estimates, with
optional grouping, faceting, split-by splitting, and data-distribution rug
bars along the baseline.
This is the public entry point for density plots; the companion
Histogram() function provides binned-histogram rendering.
Both dispatch to the same internal engine (DensityHistoPlotAtomic)
with type = "density" or type = "histogram" respectively.
Histogram for visualising the distribution of a numeric variable via binned
counts. Uses ggplot2::geom_histogram(), with optional trend-line overlays,
zero-skip interpolation, grouping, faceting, and split-by splitting.
This is the histogram companion to DensityPlot(). Both dispatch to the
same internal engine (DensityHistoPlotAtomic) with type = "histogram"
or type = "density" respectively.
When use_trend = TRUE, the histogram bars are replaced entirely by a
point-and-line trend; when add_trend = TRUE, the trend is overlaid on top
of the bars. The trend_skip_zero option uses zoo::na.approx() to
interpolate across empty bins for a continuous trend curve — particularly
useful with transformed y-axes.
Usage
DensityPlot(
data,
x,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
xtrans = "identity",
ytrans = "identity",
split_by = NULL,
split_by_sep = "_",
flip = FALSE,
position = "identity",
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 0.5,
theme = "theme_this",
theme_args = list(),
add_bars = FALSE,
bar_height = 0.025,
bar_alpha = 1,
bar_width = 0.1,
keep_na = FALSE,
keep_empty = FALSE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
expand = c(bottom = 0, left = 0, right = 0),
facet_by = NULL,
facet_scales = "free_y",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = ifelse(is.null(group_by), "none", "right"),
legend.direction = "vertical",
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Histogram(
data,
x,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
xtrans = "identity",
ytrans = "identity",
split_by = NULL,
split_by_sep = "_",
flip = FALSE,
bins = NULL,
binwidth = NULL,
trend_skip_zero = FALSE,
add_bars = FALSE,
bar_height = 0.025,
bar_alpha = 1,
bar_width = 0.1,
position = "identity",
keep_na = FALSE,
keep_empty = FALSE,
use_trend = FALSE,
add_trend = FALSE,
trend_alpha = 1,
trend_linewidth = 0.8,
trend_pt_size = 1.5,
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 0.5,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
expand = c(bottom = 0, left = 0, right = 0),
facet_by = NULL,
facet_scales = "free_y",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = ifelse(is.null(group_by), "none", "right"),
legend.direction = "vertical",
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string used as the legend title for the
|
xtrans |
A character string specifying the transformation applied to
the x-axis. Passed to |
ytrans |
A character string specifying the transformation applied to
the y-axis. Passed to |
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
flip |
A logical value. If |
position |
A character string specifying the position adjustment for
the bars or density curves. Default: |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
add_bars |
A logical value. If |
bar_height |
A numeric value specifying the height (in data units,
relative to the maximum y) of the rug bars added by |
bar_alpha |
A numeric value in |
bar_width |
A numeric value passed as the |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
seed |
The random seed to use. Default is 8525. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments. |
bins |
A numeric value specifying the number of bins for the histogram.
Ignored when |
binwidth |
A numeric value specifying the width of individual bins for
the histogram. Ignored when |
trend_skip_zero |
A logical value. If |
use_trend |
A logical value. If |
add_trend |
A logical value. If |
trend_alpha |
A numeric value in |
trend_linewidth |
A numeric value for the thickness of the trend line.
Default: |
trend_pt_size |
A numeric value for the size of the trend points.
Default: |
Value
A ggplot object (single plot), a patchwork / wrap_plots object
(when split_by is provided and combine = TRUE), or a list of ggplot
objects (when split_by is provided and combine = FALSE).
A ggplot object (single plot), a patchwork / wrap_plots object
(when split_by is provided and combine = TRUE), or a list of ggplot
objects (when split_by is provided and combine = FALSE).
split_by Workflow
When split_by is specified, DensityPlot() executes the following pipeline:
-
Argument validation —
validate_common_args()checks the seed and facet-by consistency. -
NA / empty normalisation —
check_keep_na()/check_keep_empty()convertkeep_na/keep_emptyto per-column lists. -
Theme resolution —
process_theme()resolves the theme string to a theme function. -
Split column resolution —
check_columns()validatessplit_by(force_factor, concat_multi). -
Pre-filtering —
process_keep_na_empty()removes NA / empty levels from the split column, thendatais split bysplit_bylevels (order preserved). -
Per-split parameter resolution —
check_palette(),check_palcolor(),check_legend()resolve palette, palcolor, legend.position, and legend.direction for each split. -
Per-split dispatch — each split is passed to
DensityHistoPlotAtomic(type = "density", ...)with its resolved parameters. Title defaults to the split level name unlesstitleis a function. -
Combination —
combine_plots()assembles the list of plots viapatchwork::wrap_plots(), applyingnrow,ncol,byrow,axes,axis_titles,guides, anddesign.
When split_by is specified, Histogram() executes the following pipeline:
-
Argument validation —
validate_common_args()checks the seed and facet-by consistency. -
NA / empty normalisation —
check_keep_na()/check_keep_empty()convertkeep_na/keep_emptyto per-column lists. -
Theme resolution —
process_theme()resolves the theme string to a theme function. -
Split column resolution —
check_columns()validatessplit_by(force_factor, concat_multi). -
Pre-filtering —
process_keep_na_empty()removes NA / empty levels from the split column, thendatais split bysplit_bylevels (order preserved). -
Per-split parameter resolution —
check_palette(),check_palcolor(),check_legend()resolve palette, palcolor, legend.position, and legend.direction for each split. -
Per-split dispatch — each split is passed to
DensityHistoPlotAtomic(type = "histogram", ...)with its resolved parameters (includingbins,binwidth,use_trend,add_trend,trend_skip_zero,trend_alpha,trend_linewidth,trend_pt_size). Title defaults to the split level name unlesstitleis a function. -
Combination —
combine_plots()assembles the list of plots viapatchwork::wrap_plots(), applyingnrow,ncol,byrow,axes,axis_titles,guides, anddesign.
Examples
set.seed(8525)
data <- data.frame(
x = c(rnorm(500, -1), rnorm(500, 1)),
group = factor(rep(c("A", NA, "C", "D"), each = 250), levels = LETTERS[1:4]),
facet = sample(c("F1", "F2"), 1000, replace = TRUE)
)
# basic density
DensityPlot(data, x = "x")
DensityPlot(data, x = "x", group_by = "group")
# NA / empty level handling
DensityPlot(data, x = "x", group_by = "group",
keep_na = TRUE, keep_empty = TRUE)
DensityPlot(data, x = "x", group_by = "group",
keep_na = TRUE, keep_empty = 'level')
# faceting and splitting
DensityPlot(data, x = "x", group_by = "group", facet_by = "facet")
DensityPlot(data, x = "x", split_by = "facet", add_bars = TRUE)
DensityPlot(data, x = "x", split_by = "facet", add_bars = TRUE,
palette = c(F1 = "Set1", F2 = "Set2"))
set.seed(8525)
data <- data.frame(
x = sample(setdiff(1:100, c(30:36, 50:55, 70:77)), 1000, replace = TRUE),
group = factor(rep(c("A", "B", NA, "D"), each = 250), levels = LETTERS[1:4]),
facet = sample(c("F1", "F2"), 1000, replace = TRUE)
)
# basic histogram
Histogram(data, x = "x")
Histogram(data, x = "x", group_by = "group")
# NA / empty level handling
Histogram(data, x = "x", group_by = "group", keep_na = TRUE, keep_empty = 'level')
# add_bars and trend overlays
Histogram(data, x = "x", split_by = "facet", add_bars = TRUE)
Histogram(data, x = "x", group_by = "group", add_trend = TRUE)
Histogram(data, x = "x", group_by = "group", add_trend = TRUE, trend_skip_zero = TRUE)
# use_trend replaces bars entirely
Histogram(data, x = "x", group_by = "group", split_by = "facet",
use_trend = TRUE, trend_pt_size = 3)
# per-split palettes
Histogram(data, x = "x", group_by = "group", split_by = "facet",
palette = c(F1 = "Paired", F2 = "Spectral"))
DimPlot / FeatureDimPlot
Description
DimPlot visualizes dimension reduction data (PCA, t-SNE, UMAP, etc.) as a 2D or 3D
scatter plot. DimPlot() colours points by a discrete grouping variable
(e.g., clusters), while FeatureDimPlot() colours points by a continuous
numeric feature (e.g., gene expression, lineage scores).
Both functions share the same internal engine (DimPlotAtomic) and support
an extensive set of annotation layers: group boundary marks, network/graph
edges, 2D density contours, lineage/trajectory curves, RNA-velocity arrows
(raw, grid, or stream), statistical summary mini-plots at group centroids,
point highlighting, background context points from other facets, and
flexible label positioning.
When dims has 3 elements, both functions automatically return an
interactive plotly 3D scatter plot (via DimPlotAtomic3D). Certain
2D-only features are silently ignored in 3D mode (see @param dims for
the full list).
Rendering scales with dataset size: standard geom_point() for small data,
automatic rasterisation via scattermore::geom_scattermore() when
nrow(data) > 1e5, or hex-bin aggregation (geom_hex() /
stat_summary_hex()).
FeatureDimPlot to visualize feature expression on dimension reduction plots.
Colours points by a
continuous numeric variable (e.g., gene expression, module score, lineage
pseudotime) using a gradient colour scale, with optional quantile trimming
and background cutoff.
When multiple features are provided and facet_by is not set, the data
is automatically pivoted to long format and faceted by feature name.
split_by = TRUE dispatches each feature to a separate plot for
independent layout control. split_by as a column name splits by that
column's levels, producing one plot per level with per-split palette
support.
For detailed split_by workflows, see the main DimPlot / FeatureDimPlot
documentation (@section split_by Workflow (FeatureDimPlot)).
Usage
DimPlot(
data,
dims = 1:2,
group_by,
group_by_sep = "_",
split_by = NULL,
split_by_sep = "_",
pt_size = NULL,
pt_alpha = 1,
bg_color = "grey80",
label_insitu = FALSE,
show_stat = !identical(theme, "theme_blank"),
label = FALSE,
label_size = 4,
label_fg = "white",
label_bg = "black",
label_bg_r = 0.1,
label_repel = FALSE,
label_repulsion = 20,
label_pt_size = 1,
label_pt_color = "black",
label_segment_color = "black",
order = c("as-is", "reverse", "high-top", "low-top", "random"),
highlight = NULL,
highlight_alpha = 1,
highlight_size = 1,
highlight_color = "black",
highlight_stroke = 0.8,
add_mark = FALSE,
mark_type = c("hull", "ellipse", "rect", "circle"),
mark_expand = unit(3, "mm"),
mark_alpha = 0.1,
mark_linetype = 1,
stat_by = NULL,
stat_plot_type = c("pie", "ring", "bar", "line"),
stat_plot_size = 0.1,
stat_args = list(palette = "Set1"),
graph = NULL,
edge_size = c(0.05, 0.5),
edge_alpha = 0.1,
edge_color = "grey40",
add_density = FALSE,
density_color = "grey80",
density_filled = FALSE,
density_filled_palette = "Greys",
density_filled_palcolor = NULL,
lineages = NULL,
lineages_trim = c(0.01, 0.99),
lineages_span = 0.75,
lineages_palette = "Dark2",
lineages_palcolor = NULL,
lineages_arrow = arrow(length = unit(0.1, "inches")),
lineages_linewidth = 1,
lineages_line_bg = "white",
lineages_line_bg_stroke = 0.5,
lineages_whiskers = FALSE,
lineages_whiskers_linewidth = 0.5,
lineages_whiskers_alpha = 0.5,
velocity = NULL,
velocity_plot_type = c("raw", "grid", "stream"),
velocity_n_neighbors = NULL,
velocity_density = 1,
velocity_smooth = 0.5,
velocity_scale = 1,
velocity_min_mass = 1,
velocity_cutoff_perc = 5,
velocity_group_palette = "Set2",
velocity_group_palcolor = NULL,
arrow_angle = 20,
arrow_color = "black",
arrow_alpha = 1,
streamline_l = 5,
streamline_minl = 1,
streamline_res = 1,
streamline_n = 15,
streamline_width = c(0, 0.8),
streamline_alpha = 1,
streamline_color = NULL,
streamline_palette = "RdYlBu",
streamline_palcolor = NULL,
streamline_bg_color = "white",
streamline_bg_stroke = 0.5,
keep_na = FALSE,
keep_empty = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
theme = "theme_this",
theme_args = list(),
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
raster = NULL,
raster_dpi = c(512, 512),
hex = FALSE,
hex_linewidth = 0.5,
hex_count = TRUE,
hex_bins = 50,
hex_binwidth = NULL,
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
FeatureDimPlot(
data,
dims = 1:2,
features,
split_by = NULL,
split_by_sep = "_",
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
pt_size = NULL,
pt_alpha = 1,
bg_color = "grey80",
bg_cutoff = NULL,
label_insitu = FALSE,
show_stat = !identical(theme, "theme_blank"),
color_name = "",
label = FALSE,
label_size = 4,
label_fg = "white",
label_bg = "black",
label_bg_r = 0.1,
label_repel = FALSE,
label_repulsion = 20,
label_pt_size = 1,
label_pt_color = "black",
label_segment_color = "black",
order = c("as-is", "reverse", "high-top", "low-top", "random"),
highlight = NULL,
highlight_alpha = 1,
highlight_size = 1,
highlight_color = "black",
highlight_stroke = 0.8,
add_mark = FALSE,
mark_type = c("hull", "ellipse", "rect", "circle"),
mark_expand = unit(3, "mm"),
mark_alpha = 0.1,
mark_linetype = 1,
keep_na = FALSE,
keep_empty = FALSE,
stat_by = NULL,
stat_plot_type = c("pie", "ring", "bar", "line"),
stat_plot_size = 0.1,
stat_args = list(palette = "Set1"),
graph = NULL,
edge_size = c(0.05, 0.5),
edge_alpha = 0.1,
edge_color = "grey40",
add_density = FALSE,
density_color = "grey80",
density_filled = FALSE,
density_filled_palette = "Greys",
density_filled_palcolor = NULL,
lineages = NULL,
lineages_trim = c(0.01, 0.99),
lineages_span = 0.75,
lineages_palette = "Dark2",
lineages_palcolor = NULL,
lineages_arrow = arrow(length = unit(0.1, "inches")),
lineages_linewidth = 1,
lineages_line_bg = "white",
lineages_line_bg_stroke = 0.5,
lineages_whiskers = FALSE,
lineages_whiskers_linewidth = 0.5,
lineages_whiskers_alpha = 0.5,
velocity = NULL,
velocity_plot_type = c("raw", "grid", "stream"),
velocity_n_neighbors = NULL,
velocity_density = 1,
velocity_smooth = 0.5,
velocity_scale = 1,
velocity_min_mass = 1,
velocity_cutoff_perc = 5,
velocity_group_palette = "Set2",
velocity_group_palcolor = NULL,
arrow_angle = 20,
arrow_color = "black",
arrow_alpha = 1,
streamline_l = 5,
streamline_minl = 1,
streamline_res = 1,
streamline_n = 15,
streamline_width = c(0, 0.8),
streamline_alpha = 1,
streamline_color = NULL,
streamline_palette = "RdYlBu",
streamline_palcolor = NULL,
streamline_bg_color = "white",
streamline_bg_stroke = 0.5,
facet_by = NULL,
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
theme = "theme_this",
theme_args = list(),
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
raster = NULL,
raster_dpi = c(512, 512),
hex = FALSE,
hex_linewidth = 0.5,
hex_count = FALSE,
hex_bins = 50,
hex_binwidth = NULL,
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
dims |
A character vector of the column names to plot on the x, y (and optionally z) axes or a numeric vector of the column indices. When 3 dimensions are provided, a 3D interactive plot is created using plotly. Supported in 3D: group_by, features, labels, highlight, lineages, graph/network, show_stat, order. Not supported in 3D: add_mark, stat_by, add_density, velocity, hex, facet_by, raster. |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
split_by |
A character vector of column names to split the data by and
plot separately. If |
split_by_sep |
The separator for multiple split_by columns. See |
pt_size |
A numeric value of the point size. If NULL (default), the point size is auto-calculated as
|
pt_alpha |
A numeric value in |
bg_color |
A character string specifying the colour used for NA-valued points and
background context points drawn from other facets. Default is |
label_insitu |
A logical value. If |
show_stat |
A logical value. If |
label |
A logical value. If |
label_size |
A numeric value for the label text size. Passed to |
label_fg |
A character string for the label text (foreground) colour. Default is |
label_bg |
A character string for the label background / outline colour. Default is |
label_bg_r |
A numeric value for the background fill ratio of the label bounding box.
Passed to |
label_repel |
A logical value. If |
label_repulsion |
A numeric value for the repulsion force when |
label_pt_size |
A numeric value for the size of the anchor point drawn when
|
label_pt_color |
A character string for the colour of the label anchor point. Default is |
label_segment_color |
A character string for the colour of the line segment connecting
the label to the anchor. Used in non-repel mode ( |
order |
A character string controlling the draw order of points:
For |
highlight |
A specification for highlighted points:
|
highlight_alpha |
A numeric value in |
highlight_size |
A numeric value for the size of the inner (coloured) highlight point.
Default is |
highlight_color |
A character string for the colour of the outer highlight ring.
Default is |
highlight_stroke |
A numeric value for the thickness of the outer highlight ring (the
difference between the outer ring size and |
add_mark |
A logical value. If |
mark_type |
A character string specifying the mark shape. Options:
|
mark_expand |
A unit value for the outward expansion of the mark boundary.
Passed to |
mark_alpha |
A numeric value in |
mark_linetype |
A numeric value for the line type of the mark boundary. Default is |
stat_by |
A character string naming a column used to compute per-group statistical summary
mini-plots embedded at group centroid positions. Only supported with |
stat_plot_type |
A character string specifying the mini-plot type. Options:
|
stat_plot_size |
A numeric value for the size of the stat mini-plot, expressed as a
fraction of the axis range. Default is |
stat_args |
A list of additional arguments passed to the stat plot function
(e.g., |
graph |
A specification for network / graph edges to overlay. Sources:
|
edge_size |
A numeric vector of length 2 specifying the range |
edge_alpha |
A numeric value in |
edge_color |
A character string for the colour of graph edges. Default is |
add_density |
A logical value. If |
density_color |
A character string for the colour of the density contour lines.
Used when |
density_filled |
A logical value. If |
density_filled_palette |
A character string naming the palette for the filled density layer.
Default is |
density_filled_palcolor |
A character vector of specific colours for the filled density
palette. Default is |
lineages |
A character vector of column names representing pseudotime / trajectory lineages.
Each column is fitted with a LOESS smooth ( |
lineages_trim |
A numeric vector of length 2 specifying the lower and upper quantile
thresholds |
lineages_span |
A numeric value passed as |
lineages_palette |
A character string naming the palette for lineage colours.
Default is |
lineages_palcolor |
A character vector of specific colours for lineage curves.
Default is |
lineages_arrow |
A ggplot2 |
lineages_linewidth |
A numeric value for the width of the lineage curve lines.
Default is |
lineages_line_bg |
A character string for the colour of the background (wider) stroke
drawn behind each lineage curve for improved visibility. Default is |
lineages_line_bg_stroke |
A numeric value for the additional width of the background
stroke relative to |
lineages_whiskers |
A logical value. If |
lineages_whiskers_linewidth |
A numeric value for the width of the whisker lines.
Default is |
lineages_whiskers_alpha |
A numeric value in |
velocity |
A specification for RNA-velocity arrows. Can be:
|
velocity_plot_type |
A character string specifying the velocity rendering style.
Options: |
velocity_n_neighbors |
A numeric value for the number of neighbours used in the
velocity grid computation. Default is |
velocity_density |
A numeric value for the velocity kernel density bandwidth.
Default is |
velocity_smooth |
A numeric value for the velocity smoothing parameter.
Default is |
velocity_scale |
A numeric value for scaling the velocity arrows. Default is |
velocity_min_mass |
A numeric value for the minimum cell mass threshold in velocity
grid computation. Default is |
velocity_cutoff_perc |
A numeric value for the velocity cutoff percentage.
Default is |
velocity_group_palette |
A character string naming the palette for velocity group
colours (used in |
velocity_group_palcolor |
A character vector of specific colours for velocity groups.
Default is |
arrow_angle |
A numeric value specifying the angle of the arrowheads in degrees. Applied to |
arrow_color |
A character string specifying the color of the velocity arrows. For |
arrow_alpha |
A numeric value between 0 and 1 specifying the transparency of the velocity arrows. Only used when |
streamline_l |
A numeric value specifying the integration length of the streamlines. Passed to |
streamline_minl |
A numeric value specifying the minimum streamline length. Shorter streamlines are not drawn. Passed to |
streamline_res |
A numeric value specifying the resolution of the streamline integration. Passed to |
streamline_n |
A numeric value specifying the number of streamlines to draw. Passed to |
streamline_width |
A numeric vector of length 2 specifying the range of line widths for streamlines. Passed to |
streamline_alpha |
A numeric value between 0 and 1 specifying the transparency of the velocity streamlines. Default is 1. |
streamline_color |
An optional character string specifying a fixed color for streamlines. When |
streamline_palette |
A character string specifying the color palette for streamline velocity magnitude. Passed to |
streamline_palcolor |
An optional character vector of specific colors for the streamline velocity gradient. If |
streamline_bg_color |
A character string specifying the background (outline) color applied to streamlines to create a stroke effect. Default is |
streamline_bg_stroke |
A numeric value specifying the additional line width of the background stroke relative to the foreground streamline. Default is 0.5. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
raster |
A logical value. If |
raster_dpi |
A numeric vector of length 2 |
hex |
A logical value. If |
hex_linewidth |
A numeric value for the width of the hexagon boundary lines.
Default is |
hex_count |
A logical value. If |
hex_bins |
A numeric value for the number of hex bins along each axis.
Passed to |
hex_binwidth |
A numeric value for the width of individual hex bins.
Passed to |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
seed |
The random seed to use. Default is 8525. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments. |
features |
A character vector of the column names to plot as features (continuous colouring).
When multiple features are provided and |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
bg_cutoff |
A numeric threshold. Feature values with absolute value below this
cutoff are set to |
color_name |
A character string used as the title for the continuous colour bar
in feature mode. Default is |
Value
A ggplot object (single plot), a patchwork / wrap_plots object
(when split_by is provided and combine = TRUE), or a list of ggplot
objects (when split_by is provided and combine = FALSE).
When dims has 3 elements, a plotly object is returned instead.
A ggplot object (single plot), a patchwork / wrap_plots object
(when split_by is provided and combine = TRUE), or a list of ggplot
objects (when split_by is provided and combine = FALSE).
When dims has 3 elements, a plotly object is returned instead.
split_by Workflow (DimPlot)
When split_by is specified, DimPlot() executes the following pipeline:
-
Argument validation —
validate_common_args()checks the seed and blockssplit_by+velocitycombinations. -
NA / empty normalisation —
check_keep_na()/check_keep_empty()convertkeep_na/keep_emptyto per-column lists. -
Theme resolution —
process_theme()resolves the theme string to a theme function. -
Split column resolution —
check_columns()validatessplit_by(force_factor, concat_multi). -
Pre-filtering —
process_keep_na_empty()removes NA / empty levels from the split column, thendatais split bysplit_bylevels (order preserved). Whengraphreferences an attribute (@graph), the graph matrix is also subset per split. -
Per-split parameter resolution —
check_palette(),check_palcolor(),check_legend()resolve palette, palcolor, legend.position, and legend.direction for each split. -
Per-split dispatch — each split is passed to
DimPlotAtomic()with its resolved parameters. Title defaults to the split level name unlesstitleis a function. -
Combination —
combine_plots()assembles the list of plots viapatchwork::wrap_plots(), applyingnrow,ncol,byrow,axes,axis_titles,guides, anddesign.
split_by Workflow (FeatureDimPlot)
FeatureDimPlot() supports two forms of splitting:
A. split_by = TRUE (split by features)
Each feature in
featuresis dispatched individually toDimPlotAtomic(), producing one plot per feature. The plot title defaults to the feature name.Plots are combined via
combine_plots()withsplit_by = ".features".
B. split_by as a column name (split by data column)
Data is split by the named column's levels (same pipeline as DimPlot steps 1–8 above). Graph attribute splitting is supported.
See Also
Examples
data(dim_example)
# basic dim plot
DimPlot(dim_example, group_by = "clusters")
DimPlot(dim_example, group_by = "clusters", theme = "theme_blank")
DimPlot(dim_example, group_by = "clusters", theme = ggplot2::theme_classic,
theme_args = list(base_size = 16), palette = "seurat")
# raster and highlighting
DimPlot(dim_example, group_by = "clusters", raster = TRUE, raster_dpi = 50)
DimPlot(dim_example, group_by = "clusters", highlight = 1:20,
highlight_color = "black", highlight_stroke = 2)
DimPlot(dim_example, group_by = "clusters", highlight = TRUE, facet_by = "group",
theme = "theme_blank")
# labels
DimPlot(dim_example, group_by = "clusters", label = TRUE,
label_size = 5, label_bg_r = 0.2)
DimPlot(dim_example, group_by = "clusters", label = TRUE, label_fg = "red",
label_bg = "yellow", label_size = 5)
DimPlot(dim_example, group_by = "clusters", label = TRUE, label_insitu = TRUE)
# group marks
DimPlot(dim_example, group_by = "clusters", add_mark = TRUE)
DimPlot(dim_example, group_by = "clusters", add_mark = TRUE, mark_linetype = 2)
DimPlot(dim_example, group_by = "clusters", add_mark = TRUE, mark_type = "ellipse")
# density overlays
DimPlot(dim_example, group_by = "clusters", add_density = TRUE)
DimPlot(dim_example, group_by = "clusters", add_density = TRUE, density_filled = TRUE)
DimPlot(dim_example, group_by = "clusters", add_density = TRUE, density_filled = TRUE,
density_filled_palette = "Blues", highlight = TRUE)
# statistics at group centroids
DimPlot(dim_example, group_by = "clusters", stat_by = "group")
DimPlot(dim_example, group_by = "clusters", stat_by = "group",
stat_plot_type = "bar", stat_plot_size = 0.06)
# hex bins
DimPlot(dim_example, group_by = "clusters", hex = TRUE)
DimPlot(dim_example, group_by = "clusters", hex = TRUE, hex_bins = 20)
DimPlot(dim_example, group_by = "clusters", hex = TRUE, hex_count = FALSE)
# graph / network edges
DimPlot(dim_example, group_by = "clusters", graph = "@graph", edge_color = "grey80")
# lineages / trajectories
DimPlot(dim_example, group_by = "clusters", lineages = c("stochasticbasis_1", "stochasticbasis_2"))
DimPlot(dim_example, group_by = "clusters", lineages = c("stochasticbasis_1", "stochasticbasis_2"),
lineages_whiskers = TRUE, lineages_whiskers_linewidth = 0.1)
DimPlot(dim_example, group_by = "clusters", lineages = c("stochasticbasis_1", "stochasticbasis_2"),
lineages_span = 0.4)
# split_by
DimPlot(dim_example, group_by = "clusters", split_by = "group",
palette = list(A = "Paired", B = "Set1"))
# velocity
DimPlot(dim_example, group_by = "clusters", velocity = c("stochasticbasis_1", "stochasticbasis_2"),
pt_alpha = 0)
DimPlot(dim_example, group_by = "clusters", velocity = 3:4,
velocity_plot_type = "grid", arrow_alpha = 0.6)
DimPlot(dim_example, group_by = "clusters", velocity = 3:4,
velocity_plot_type = "stream")
# 3D plots (returns a plotly object)
DimPlot(dim_example, dims = 1:3, group_by = "clusters")
DimPlot(dim_example, dims = 1:3, group_by = "clusters", label = TRUE,
label_insitu = TRUE)
DimPlot(dim_example, dims = c("basis_1", "basis_2", "stochasticbasis_1"),
group_by = "clusters", graph = "@graph", edge_color = "grey80")
# keep_na and keep_empty
dim_example$clusters[dim_example$clusters == "Ductal"] <- NA
DimPlot(dim_example, group_by = "clusters", keep_na = FALSE, keep_empty = TRUE)
DimPlot(dim_example, group_by = "clusters", keep_na = TRUE, keep_empty = TRUE)
DimPlot(dim_example, group_by = "clusters", keep_na = TRUE, keep_empty = FALSE)
data(dim_example)
# single feature
FeatureDimPlot(dim_example, features = "stochasticbasis_1", pt_size = 2)
FeatureDimPlot(dim_example, features = "stochasticbasis_1", pt_size = 2, bg_cutoff = 0)
FeatureDimPlot(dim_example, features = "stochasticbasis_1", raster = TRUE, raster_dpi = 30)
# multiple features (auto-pivoted to long, faceted by feature)
FeatureDimPlot(dim_example, features = c("stochasticbasis_1", "stochasticbasis_2"),
pt_size = 2)
# single feature with facet_by (facet_by works when only 1 feature)
FeatureDimPlot(dim_example, features = c("stochasticbasis_1"), pt_size = 2,
facet_by = "group")
# multiple features with split_by for independent layout
FeatureDimPlot(dim_example, features = c("stochasticbasis_1", "stochasticbasis_2"),
split_by = "group", nrow = 2)
# highlight and hex
FeatureDimPlot(dim_example, features = c("stochasticbasis_1", "stochasticbasis_2"),
highlight = TRUE)
FeatureDimPlot(dim_example, features = c("stochasticbasis_1", "stochasticbasis_2"),
hex = TRUE, hex_bins = 15)
FeatureDimPlot(dim_example, features = c("stochasticbasis_1", "stochasticbasis_2"),
hex = TRUE, hex_bins = 15, split_by = "group", palette = list(A = "Reds", B = "Blues"))
# 3D plots (returns a plotly object)
FeatureDimPlot(dim_example, dims = 1:3, features = "stochasticbasis_2", pt_size = 2)
FeatureDimPlot(dim_example, dims = c("basis_1", "basis_2", "stochasticbasis_1"),
features = "stochasticbasis_2")
Atomic Dimension Reduction Plot without splitting the data
Description
Core implementation for dimension reduction visualisation. This is the
internal workhorse dispatched by both DimPlot() (group-based) and
FeatureDimPlot() (continuous feature expression). It renders a 2D
scatter plot of ordination axes with extensive annotation capabilities,
and automatically delegates to DimPlotAtomic3D() for interactive 3D
plots when three dims are provided.
The function supports two primary colouring modes:
-
group_by — discrete factor colouring with a legend of group levels, optional density/statistical overlays, and group mark / label annotations.
-
features — continuous numeric colouring with a gradient colour bar, multi-feature faceting via
tidyr::pivot_longer(), and optional cutoff / quantile trimming viaprepare_continuous_color_scale().
Additional annotation layers include: graph / network edges drawn as
segments between connected nodes, 2D density contours (filled or outline),
group marks (hull, ellipse, rect, circle via ggforce), lineage curves
(LOESS-smoothed paths with optional whiskers), velocity / RNA-velocity
arrows (raw, grid, or stream via VelocityPlot()), statistical summary
mini-plots (pie, ring, bar, line) embedded at group centroids, background
points from other facets (faded context), and group labels with repulsion
(via ggrepel::geom_text_repel()).
Rendering scales automatically: scatter points for small datasets,
scattermore::geom_scattermore() raster for n > 1e5, or hex-binned
aggregation (stat_summary_hex() / geom_hex()). Legend assembly uses
cowplot::get_plot_component() with independent guide-boxes for base
groups, lineages, velocity, and stat-by annotations — combined via
rbind / cbind and re-inserted with add_grob().
Usage
DimPlotAtomic(
data,
dims = 1:2,
group_by = NULL,
group_by_sep = "_",
features = NULL,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
pt_size = NULL,
pt_alpha = 1,
bg_color = "grey80",
bg_cutoff = NULL,
color_name = "",
label_insitu = FALSE,
show_stat = !identical(theme, "theme_blank"),
label = FALSE,
label_size = 4,
label_fg = "white",
label_bg = "black",
label_bg_r = 0.1,
label_repel = FALSE,
label_repulsion = 20,
label_pt_size = 1,
label_pt_color = "black",
label_segment_color = "black",
order = c("as-is", "reverse", "high-top", "low-top", "random"),
highlight = NULL,
highlight_alpha = 1,
highlight_size = 1,
highlight_color = "black",
highlight_stroke = 0.8,
add_mark = FALSE,
mark_type = c("hull", "ellipse", "rect", "circle"),
mark_expand = unit(3, "mm"),
mark_alpha = 0.1,
mark_linetype = 1,
stat_by = NULL,
stat_plot_type = c("pie", "ring", "bar", "line"),
stat_plot_size = 0.1,
stat_palette = "Set1",
stat_args = list(),
graph = NULL,
edge_size = c(0.05, 0.5),
edge_alpha = 0.1,
edge_color = "grey40",
add_density = FALSE,
density_color = "grey80",
density_filled = FALSE,
density_filled_palette = "Greys",
density_filled_palcolor = NULL,
lineages = NULL,
lineages_trim = c(0.01, 0.99),
lineages_span = 0.75,
lineages_palette = "Dark2",
lineages_palcolor = NULL,
lineages_arrow = ggplot2::arrow(length = unit(0.1, "inches")),
lineages_linewidth = 1,
lineages_line_bg = "white",
lineages_line_bg_stroke = 0.5,
lineages_whiskers = FALSE,
lineages_whiskers_linewidth = 0.5,
lineages_whiskers_alpha = 0.5,
velocity = NULL,
velocity_plot_type = c("raw", "grid", "stream"),
velocity_n_neighbors = NULL,
velocity_density = 1,
velocity_smooth = 0.5,
velocity_scale = 1,
velocity_min_mass = 1,
velocity_cutoff_perc = 5,
velocity_group_palette = "Set2",
velocity_group_palcolor = NULL,
arrow_angle = 20,
arrow_color = "black",
streamline_l = 5,
streamline_minl = 1,
streamline_res = 1,
streamline_n = 15,
arrow_alpha = 1,
streamline_width = c(0, 0.8),
streamline_alpha = 1,
streamline_color = NULL,
streamline_palette = "RdYlBu",
streamline_palcolor = NULL,
streamline_bg_color = "white",
streamline_bg_stroke = 0.5,
keep_na = FALSE,
keep_empty = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
theme = "theme_this",
theme_args = list(),
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
raster = NULL,
raster_dpi = c(512, 512),
hex = FALSE,
hex_linewidth = 0.5,
hex_count = !is.null(group_by),
hex_bins = 50,
hex_binwidth = NULL,
palette = ifelse(is.null(features), "Paired", "Spectral"),
palcolor = NULL,
palreverse = FALSE,
seed = 8525,
...
)
Arguments
data |
A data frame. |
dims |
A character vector of the column names to plot on the x, y (and optionally z) axes or a numeric vector of the column indices. When 3 dimensions are provided, a 3D interactive plot is created using plotly. Supported in 3D: group_by, features, labels, highlight, lineages, graph/network, show_stat, order. Not supported in 3D: add_mark, stat_by, add_density, velocity, hex, facet_by, raster. |
group_by |
A character string of the column name to group the data by for discrete colouring.
A character/factor column is expected. If multiple columns are provided, the columns will be concatenated with |
group_by_sep |
A character string to concatenate the columns in |
features |
A character vector of the column names to plot as features (continuous colouring).
When multiple features are provided and |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
pt_size |
A numeric value of the point size. If NULL (default), the point size is auto-calculated as
|
pt_alpha |
A numeric value in |
bg_color |
A character string specifying the colour used for NA-valued points and
background context points drawn from other facets. Default is |
bg_cutoff |
A numeric threshold. Feature values with absolute value below this
cutoff are set to |
color_name |
A character string used as the title for the continuous colour bar
in feature mode. Default is |
label_insitu |
A logical value. If |
show_stat |
A logical value. If |
label |
A logical value. If |
label_size |
A numeric value for the label text size. Passed to |
label_fg |
A character string for the label text (foreground) colour. Default is |
label_bg |
A character string for the label background / outline colour. Default is |
label_bg_r |
A numeric value for the background fill ratio of the label bounding box.
Passed to |
label_repel |
A logical value. If |
label_repulsion |
A numeric value for the repulsion force when |
label_pt_size |
A numeric value for the size of the anchor point drawn when
|
label_pt_color |
A character string for the colour of the label anchor point. Default is |
label_segment_color |
A character string for the colour of the line segment connecting
the label to the anchor. Used in non-repel mode ( |
order |
A character string controlling the draw order of points:
For |
highlight |
A specification for highlighted points:
|
highlight_alpha |
A numeric value in |
highlight_size |
A numeric value for the size of the inner (coloured) highlight point.
Default is |
highlight_color |
A character string for the colour of the outer highlight ring.
Default is |
highlight_stroke |
A numeric value for the thickness of the outer highlight ring (the
difference between the outer ring size and |
add_mark |
A logical value. If |
mark_type |
A character string specifying the mark shape. Options:
|
mark_expand |
A unit value for the outward expansion of the mark boundary.
Passed to |
mark_alpha |
A numeric value in |
mark_linetype |
A numeric value for the line type of the mark boundary. Default is |
stat_by |
A character string naming a column used to compute per-group statistical summary
mini-plots embedded at group centroid positions. Only supported with |
stat_plot_type |
A character string specifying the mini-plot type. Options:
|
stat_plot_size |
A numeric value for the size of the stat mini-plot, expressed as a
fraction of the axis range. Default is |
stat_args |
A list of additional arguments passed to the stat plot function
(e.g., |
graph |
A specification for network / graph edges to overlay. Sources:
|
edge_size |
A numeric vector of length 2 specifying the range |
edge_alpha |
A numeric value in |
edge_color |
A character string for the colour of graph edges. Default is |
add_density |
A logical value. If |
density_color |
A character string for the colour of the density contour lines.
Used when |
density_filled |
A logical value. If |
density_filled_palette |
A character string naming the palette for the filled density layer.
Default is |
density_filled_palcolor |
A character vector of specific colours for the filled density
palette. Default is |
lineages |
A character vector of column names representing pseudotime / trajectory lineages.
Each column is fitted with a LOESS smooth ( |
lineages_trim |
A numeric vector of length 2 specifying the lower and upper quantile
thresholds |
lineages_span |
A numeric value passed as |
lineages_palette |
A character string naming the palette for lineage colours.
Default is |
lineages_palcolor |
A character vector of specific colours for lineage curves.
Default is |
lineages_arrow |
A ggplot2 |
lineages_linewidth |
A numeric value for the width of the lineage curve lines.
Default is |
lineages_line_bg |
A character string for the colour of the background (wider) stroke
drawn behind each lineage curve for improved visibility. Default is |
lineages_line_bg_stroke |
A numeric value for the additional width of the background
stroke relative to |
lineages_whiskers |
A logical value. If |
lineages_whiskers_linewidth |
A numeric value for the width of the whisker lines.
Default is |
lineages_whiskers_alpha |
A numeric value in |
velocity |
A specification for RNA-velocity arrows. Can be:
|
velocity_plot_type |
A character string specifying the velocity rendering style.
Options: |
velocity_n_neighbors |
A numeric value for the number of neighbours used in the
velocity grid computation. Default is |
velocity_density |
A numeric value for the velocity kernel density bandwidth.
Default is |
velocity_smooth |
A numeric value for the velocity smoothing parameter.
Default is |
velocity_scale |
A numeric value for scaling the velocity arrows. Default is |
velocity_min_mass |
A numeric value for the minimum cell mass threshold in velocity
grid computation. Default is |
velocity_cutoff_perc |
A numeric value for the velocity cutoff percentage.
Default is |
velocity_group_palette |
A character string naming the palette for velocity group
colours (used in |
velocity_group_palcolor |
A character vector of specific colours for velocity groups.
Default is |
arrow_angle |
A numeric value specifying the angle of the arrowheads in degrees. Applied to |
arrow_color |
A character string specifying the color of the velocity arrows. For |
streamline_l |
A numeric value specifying the integration length of the streamlines. Passed to |
streamline_minl |
A numeric value specifying the minimum streamline length. Shorter streamlines are not drawn. Passed to |
streamline_res |
A numeric value specifying the resolution of the streamline integration. Passed to |
streamline_n |
A numeric value specifying the number of streamlines to draw. Passed to |
arrow_alpha |
A numeric value between 0 and 1 specifying the transparency of the velocity arrows. Only used when |
streamline_width |
A numeric vector of length 2 specifying the range of line widths for streamlines. Passed to |
streamline_alpha |
A numeric value between 0 and 1 specifying the transparency of the velocity streamlines. Default is 1. |
streamline_color |
An optional character string specifying a fixed color for streamlines. When |
streamline_palette |
A character string specifying the color palette for streamline velocity magnitude. Passed to |
streamline_palcolor |
An optional character vector of specific colors for the streamline velocity gradient. If |
streamline_bg_color |
A character string specifying the background (outline) color applied to streamlines to create a stroke effect. Default is |
streamline_bg_stroke |
A numeric value specifying the additional line width of the background stroke relative to the foreground streamline. Default is 0.5. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
raster |
A logical value. If |
raster_dpi |
A numeric vector of length 2 |
hex |
A logical value. If |
hex_linewidth |
A numeric value for the width of the hexagon boundary lines.
Default is |
hex_count |
A logical value. If |
hex_bins |
A numeric value for the number of hex bins along each axis.
Passed to |
hex_binwidth |
A numeric value for the width of individual hex bins.
Passed to |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object or a plotly object (when 3 dimensions are provided)
Architecture
DimPlotAtomic executes the following steps:
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplot. -
Order validation —
match.arg(order). -
Dimension resolution — converts numeric indices to column names, validates exactly 2 or 3 dims via
check_columns(). -
Column resolution — validates
group_by(force_factor, concat_multi),features, andfacet_by. Requires at least one ofgroup_byorfeatures. Blocksfacet_bywhen multiple features are present (features themselves become facets). -
Auto defaults —
pt_sizedefaults tomin(3000 / nrow(data), 0.6);rasterauto-enables whennrow(data) > 1e5;theme_blanksuppresses axis labels. -
Label force-enable — if
label_repelorlabel_insituisTRUE,labelis forced toTRUEwith a message. -
NA / empty handling —
process_keep_na_empty()filters the data;keep_emptyvalues extracted for group_by and facet_by. -
group_by preprocessing — group values / colours resolved via
palette_this(). NA levels mapped to literal"NA"string.label_useis constructed based onlabel,label_insitu, andshow_statcombinations. Facet labeller is set toas_labeller()with per-facet N annotations whenshow_stat = TRUE. -
Multi-feature pivot — when
length(features) > 1, data is pivoted to long format viatidyr::pivot_longer()with.featureas the facet variable and.valueas the numeric column. -
Continuous colour scale — when
featuresis set,prepare_continuous_color_scale()applies quantile/cutoff trimming and returns anchor values for the gradient. -
Point ordering — applies the selected
orderstrategy (as-is, reverse, high-top, low-top, random) by sorting or shuffling rows. -
3D branch — if
length(dims) == 3, emits a warning for unsupported features, optionally down-samples with stratified group sampling (whenraster = TRUE), and delegates toDimPlotAtomic3D(). -
Group marks (2D only, when
add_mark = TRUE) — dispatches toggforce::geom_mark_hull/ellipse/rect/circle, withnew_scale_fill()/new_scale_color()to isolate mark scales. -
Graph / network (2D only) — resolves the graph source (same logic as 3D), melts the matrix, handles faceted data by per-facet edge splitting, and adds
geom_segment(aes(linewidth = value))withscale_linewidth_continuous(). -
Density overlay (2D only) — filled (
stat_density_2d(geom = "raster")) or outline (geom_density_2d()). -
Base scales and theme — x / y limits from data range,
do_call(theme, theme_args), aspect ratio and legend position. -
Background points for facet context — for faceted plots (excluding multi-feature auto-faceting), points from other facets are added as faded background (raster / hex / point depending on settings).
-
Main point layer — dispatches by rendering mode:
-
raster:
scattermore::geom_scattermore()with separate NA / non-NA group layers. -
hex:
geom_hex()(group_by with optional count alpha, orstat_summary_hex()for features). Raiseshas_fill = TRUE. -
standard:
geom_point().
-
-
Highlight (2D only) — resolves highlight specification (TRUE, filter expression, row names, indices), errors on hex + highlight combo, renders highlight points with stroke (outer ring + inner colour).
-
Colour scales —
scale_color_manual()for group_by (withkeep_empty-awarebreaks/limits/drop), orscale_color_gradientn()for features.scale_fill_manual()/scale_fill_gradientn()added whenhas_fillis TRUE. -
Base legend — extracted via
cowplot::get_plot_component("guide-box-bottom"). -
Lineages (2D only, no facet_by) — per-lineage LOESS fitting (
span = lineages_span, degree = 2) with optional whiskers connecting smoothed to raw coordinates. Rendered asgeom_path()with background stroke + foreground colour, plusscale_color_manual(). Legend extracted as a separate guide-box. -
Velocity (2D only, no facet_by) — delegates to
VelocityPlot()withreturn_layer = TRUE. Addsnew_scale_color()when the velocity layer has its own colour scale. Legend extracted separately. -
Stat-by mini-plots (2D only, no facet_by, no features) — dispatches to
PieChart()/RingPlot()/BarPlot()/LinePlot()viado_call(). Each mini-plot is rendered asannotation_custom()at the group's median coordinates, scaled bystat_plot_size * range. Legend extracted from the stat plot. -
Group labels (2D only, no features) —
geom_text_repel()with optional repulsion (force = label_repulsion) or fixed segments (force = 0, bold,min.segment.length = 0). Labels positioned at group median coordinates (computed per facet if applicable). -
Legend assembly — when additional legends exist (lineages, velocity, stat_by), they are combined with the base legend via
cbind(vertical direction) orrbind(horizontal). The combined legend is re-inserted viaadd_grob(gtable, legend, legend.position). -
Dimension calculation —
calculate_plot_dimensions(base_height = 5.5, aspect.ratio, legend_n, legend_nchar)setsheight/widthattributes. -
Faceting —
facet_plot()is called only when no additional legends were assembled (otherwise the combined-legend grob is returned directly).
Internal helper to create a 3D dimension reduction plot using plotly
Description
Renders an interactive 3D scatter plot via plotly for dimension reduction
data with three ordination axes. Called automatically by DimPlotAtomic()
when length(dims) == 3.
The function supports two visualisation modes:
-
group_by — discrete group colouring with one trace per group, matching the 2D legend behaviour via
label_use. -
features — continuous colour scale with a
plotlycolorscale bar.
Graphs / networks are rendered as 3D line segments (with NA separators for
line breaks). Lineage curves are fitted via stats::loess() per lineage
column and drawn as smoothed paths. For datasets exceeding 100 000 points,
per-point hover text is disabled to reduce the JSON payload.
Usage
DimPlotAtomic3D(
data,
dims,
group_by = NULL,
features = NULL,
colorby,
colors = NULL,
feat_colors_value = NULL,
label_use = NULL,
labels_tb = NULL,
keep_empty_group = FALSE,
bg_color = "grey80",
color_name = "",
pt_size = NULL,
pt_alpha = 1,
show_stat = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
label = FALSE,
label_insitu = FALSE,
label_size = 4,
label_fg = "white",
label_bg = "black",
highlight = NULL,
highlight_color = "black",
highlight_size = 1,
highlight_stroke = 0.8,
highlight_alpha = 1,
graph = NULL,
edge_size = c(0.05, 0.5),
edge_alpha = 0.1,
edge_color = "grey40",
lineages = NULL,
lineages_trim = c(0.01, 0.99),
lineages_span = 0.75,
lineages_palette = "Dark2",
lineages_palcolor = NULL,
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
n_sampled = NULL
)
Arguments
data |
A data frame. |
dims |
A character vector of the column names to plot on the x, y (and optionally z) axes or a numeric vector of the column indices. When 3 dimensions are provided, a 3D interactive plot is created using plotly. Supported in 3D: group_by, features, labels, highlight, lineages, graph/network, show_stat, order. Not supported in 3D: add_mark, stat_by, add_density, velocity, hex, facet_by, raster. |
group_by |
A character string of the column name to group the data by for discrete colouring.
A character/factor column is expected. If multiple columns are provided, the columns will be concatenated with |
features |
A character vector of the column names to plot as features (continuous colouring).
When multiple features are provided and |
colorby |
A character string naming the column used for colour mapping
(either the |
colors |
A named character vector mapping group levels to hex colours. Only used in group_by mode. |
feat_colors_value |
A numeric vector of the colour-scale anchor values
for feature mode, as returned by |
label_use |
A character vector of formatted legend labels (with optional count annotations) used in group_by mode. |
labels_tb |
A table of group counts for trace iteration in group_by mode. |
keep_empty_group |
A logical value. If |
bg_color |
A character string specifying the colour used for NA-valued points and
background context points drawn from other facets. Default is |
color_name |
A character string used as the title for the continuous colour bar
in feature mode. Default is |
pt_size |
A numeric value of the point size. If NULL (default), the point size is auto-calculated as
|
pt_alpha |
A numeric value in |
show_stat |
A logical value. If |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
label |
A logical value. If |
label_insitu |
A logical value. If |
label_size |
A numeric value for the label text size. Passed to |
label_fg |
A character string for the label text (foreground) colour. Default is |
label_bg |
A character string for the label background / outline colour. Default is |
highlight |
A specification for highlighted points:
|
highlight_color |
A character string for the colour of the outer highlight ring.
Default is |
highlight_size |
A numeric value for the size of the inner (coloured) highlight point.
Default is |
highlight_stroke |
A numeric value for the thickness of the outer highlight ring (the
difference between the outer ring size and |
highlight_alpha |
A numeric value in |
graph |
A specification for network / graph edges to overlay. Sources:
|
edge_size |
A numeric vector of length 2 specifying the range |
edge_alpha |
A numeric value in |
edge_color |
A character string for the colour of graph edges. Default is |
lineages |
A character vector of column names representing pseudotime / trajectory lineages.
Each column is fitted with a LOESS smooth ( |
lineages_trim |
A numeric vector of length 2 specifying the lower and upper quantile
thresholds |
lineages_span |
A numeric value passed as |
lineages_palette |
A character string naming the palette for lineage colours.
Default is |
lineages_palcolor |
A character vector of specific colours for lineage curves.
Default is |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
n_sampled |
An integer indicating how many points were retained after
down-sampling (displayed in the subtitle). |
Architecture
DimPlotAtomic3D executes the following steps:
-
plotly availability check — errors early if the
plotlypackage is not installed. -
Axis labels — defaults
xlab/ylab/zlabfromdims. -
Marker size scaling — multiplies
pt_sizeby 2 to convert from ggplot2 mm units to plotly pixel units. -
Large-data detection — disables per-point hover text when
nrow(data) > 1e5. -
Base plotly object —
plotly::plot_ly()initialisation. -
Graph / network edges (if
graphis provided) — resolves the graph source (@attribute, Graph object, matrix, data.frame, column indices, or column names), aligns row/column names withdata, sets upper-triangle and zero entries toNA, melts into an edge data frame, builds x/y/z coordinate vectors (interleaved with NA for line breaks), and addsscatter3dline traces. -
Main scatter traces:
-
group_by mode: iterates over
labels_tbentries, creating one trace per group with the resolved colour. NA groups usebg_color. Legend labels uselabel_use(with count annotations ifshow_stat = TRUE). -
features mode: builds a plotly-style colorscale from the continuous palette. NA points are rendered first in
bg_colorwithout a colour bar; non-NA points follow with ashowscale = TRUEcolour bar.
-
-
Highlight — if
highlightis specified, highlighted points are plotted as open circles with increased marker size (to account for stroke). SupportsTRUE(all points), a filter expression string, or a vector of row names / numeric indices. -
Lineages — each lineage column is validated, trimmed to
[lineages_trim[1], lineages_trim[2]]quantiles, ordered by value, and aloess(span = lineages_span, degree = 2)smooth is fitted per dimension. The smoothed curve is rendered as a 3D line trace. -
Labels — when
label = TRUEandgroup_byis set, group median coordinates are computed viaaggregate(). In 3D, plotly does not support text background/outline, solabel_bgis used directly as the text colour. Text size is scaled by 3× for plotly. -
Layout — subtitle is composited with an optional "Showing N sampled points" note. The full title is rendered as HTML (
<br><sup>...</sup>). The scene setsaspectratio = list(x = 1, y = 1, z = 1)and axis titles.
Dot Plot, Scatter Plot, and Lollipop Plot
Description
DotPlot() renders a matrix of filled circles (dot plot) where dot
size encodes one numeric variable and fill colour encodes another. Either
axis can be numeric or factor, enabling four layout combinations:
-
Both axes factor — a classic dot matrix (e.g. genes × cell types), where each cell is a dot whose size reflects expression magnitude and whose colour reflects a summary statistic.
-
Both axes numeric — a scatter plot, with dots positioned by x/y coordinates, sized by a third variable, and coloured by a fourth.
-
One numeric, one factor — a strip plot or (with
lollipop = TRUE) a lollipop chart.
LollipopPlot() is a convenience wrapper that sets
lollipop = TRUE, producing horizontal bars from the y-axis to each
data point, capped by filled dots. It expects a numeric x and a
factor/character y.
Key features:
-
Auto-count: when
size_by = NULL, the per-combination observation count is computed automatically. -
fill_cutoff: values in
fill_bymatching a threshold expression (e.g."< 18") are greyed out with a dedicated legend entry. -
Background stripes:
add_bg = TRUEdraws alternating background bands along the discrete axis for visual grouping. -
Border modes:
border_colorcan track the fill gradient (TRUE), use a constant colour ("black"), or be suppressed (FALSE). -
Colour scale trimming:
lower_quantile/upper_quantile(or explicitlower_cutoff/upper_cutoff) trim the continuous fill scale extremes.
LollipopPlot() is a convenience wrapper around DotPlot()
that sets lollipop = TRUE. It renders a horizontal bar extending
from the y-axis (x = 0) to each data point, capped by a filled dot.
The bar has a two-layer construction: an outer shadow (black or custom
colour) and an inner coloured segment that follows the fill_by
gradient. Dot size scales by size_by (or the per-combination
observation count when size_by = NULL).
Expects x to be a numeric column and y to be a factor or
character column.
Usage
DotPlot(
data,
x,
y,
x_sep = "_",
y_sep = "_",
flip = FALSE,
split_by = NULL,
split_by_sep = "_",
size_name = NULL,
fill_name = NULL,
fill_cutoff_name = NULL,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
bg_direction = c("vertical", "horizontal", "v", "h"),
size_by = NULL,
fill_by = NULL,
fill_cutoff = NULL,
palreverse = FALSE,
size_min = 1,
size_max = 10,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
alpha = 1,
border_color = "black",
border_size = 0.5,
border_alpha = 1,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
x_text_angle = 0,
seed = 8525,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
LollipopPlot(
data,
x,
y,
y_sep = NULL,
flip = FALSE,
split_by = NULL,
split_by_sep = "_",
size_name = NULL,
fill_name = NULL,
fill_cutoff_name = NULL,
size_by = NULL,
fill_by = NULL,
fill_cutoff = NULL,
palreverse = FALSE,
size_min = 1,
size_max = 10,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
alpha = 1,
border_color = "black",
border_size = 0.5,
border_alpha = 1,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
x_text_angle = 0,
seed = 8525,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string naming the column for the x-axis. Must be a numeric column (bars extend from 0 to the data value). |
y |
A character string naming the column for the y-axis. Must be a factor or character column (each level gets a lollipop bar). |
x_sep |
A character string used to join multiple |
y_sep |
A character string used to join multiple |
flip |
A logical value. If |
split_by |
The column(s) to split data by and generate separate plots
for each level. The split column is processed for |
split_by_sep |
A character string used to concatenate multiple
|
size_name |
A character string for the size legend title. When
|
fill_name |
A character string for the fill colour-bar legend title.
When |
fill_cutoff_name |
A character string for the fill cutoff legend title
(shown when |
add_bg |
A logical value. If |
bg_palette |
A character string specifying the palette for the
background stripe colours. Passed to |
bg_palcolor |
A character vector of colours for the background stripes.
Passed to |
bg_alpha |
A numeric value in |
bg_direction |
A character string specifying which axis receives the
alternating background stripes. |
size_by |
A character string naming a numeric column whose values
control dot size. When |
fill_by |
A character string naming a numeric column whose values
control the fill colour of the dots (and lollipop inner bars). A
continuous gradient from |
fill_cutoff |
A string expression specifying which values of
|
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
size_min |
A numeric value for the smallest dot size in the
|
size_max |
A numeric value for the largest dot size in the
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
border_color |
Controls the dot border colour and lollipop outer-shadow appearance:
|
border_size |
A numeric value for the stroke width of dot borders and
the base linewidth of lollipop bars. In lollipop mode, the outer shadow
uses |
border_alpha |
A numeric value in |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
seed |
The random seed for reproducibility. Passed to
|
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
combine |
A logical value. If |
nrow, ncol, byrow |
Integers controlling the layout of combined plots via
|
axes, axis_titles |
Strings controlling how axes and axis titles are
handled across combined plots. Passed to |
guides |
A string controlling guide collection across combined plots.
Passed to |
design |
A custom layout specification for combined plots. Passed to
|
... |
Additional arguments. |
Value
A ggplot object (single plot), a patchwork object
(when combine = TRUE with split_by), or a list of
ggplot objects (when combine = FALSE).
A ggplot object (single plot), a patchwork object
(when combine = TRUE with split_by), or a list of
ggplot objects (when combine = FALSE).
split_by Workflow (DotPlot)
When split_by is provided, the following pipeline executes:
-
Column validation —
check_columns()resolvessplit_by(force_factor, allow_multi, concat_multi). -
NA / empty pre-processing —
process_keep_na_empty()handleskeep_na/keep_emptyfor the split column before splitting, then removes the split column from the per-splitkeep_na/keep_emptylists. -
Data splitting — splits
databysplit_bylevels (preserving factor level order). -
Per-split palette / colour —
check_palette()andcheck_palcolor()resolve per-split palette and colour overrides. -
Per-split legend —
check_legend()resolveslegend.positionandlegend.directionper split. -
Per-split title — when
titleis a function, it receives the default title (the split level name) and can return a custom string; otherwisetitle %||% split_levelis used. -
Dispatch — each split subset is passed to
DotPlotAtomic(withlollipop = FALSE). -
Combination —
combine_plots()assembles the list of plots viapatchwork::wrap_plots, honouringnrow/ncol/byrow/design.
split_by Workflow (LollipopPlot)
Same pipeline as DotPlot above, but dispatches to
DotPlotAtomic with lollipop = TRUE.
Examples
mtcars <- datasets::mtcars
mtcars$carb <- factor(mtcars$carb)
mtcars$gear <- factor(mtcars$gear)
# --- Basic dot plot (factor × factor, size + fill) ---
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18")
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "> 18")
# --- Background stripes ---
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18", add_bg = TRUE)
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18", add_bg = TRUE,
bg_direction = "h")
# --- Faceting ---
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18", facet_by = "cyl")
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18", facet_by = "cyl",
facet_scales = "free_x")
# --- split_by ---
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18", split_by = "cyl")
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18", split_by = "cyl",
palette = list("4" = "Set1", "6" = "Paired", "8" = "Reds"))
# --- Scatter plot (both axes numeric) ---
DotPlot(mtcars, x = "qsec", y = "drat", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18",
fill_cutoff_name = "Small mpgs")
# --- keep_na and keep_empty ---
mtcars$carb[mtcars$carb == "1"] <- NA
mtcars$gear[mtcars$gear == "3"] <- NA
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18",
keep_na = TRUE, keep_empty = TRUE)
# --- Border customization ---
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", border_color = "red", border_size = 2)
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", border_color = TRUE, border_size = 1.5,
border_alpha = 0.5)
DotPlot(mtcars, x = "carb", y = "gear",
fill_by = "mpg", border_color = FALSE)
# --- Colour scale trimming ---
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", lower_quantile = 0.05, upper_quantile = 0.95)
DotPlot(mtcars, x = "carb", y = "gear", size_by = "wt",
fill_by = "mpg", lower_cutoff = 15, upper_cutoff = 25)
mtcars <- datasets::mtcars
# --- Basic lollipop ---
LollipopPlot(mtcars, x = "qsec", y = "drat", size_by = "wt",
fill_by = "mpg")
# --- Faceting ---
LollipopPlot(mtcars, x = "qsec", y = "drat", size_by = "wt",
fill_by = "mpg", fill_cutoff = "< 18", facet_by = "cyl",
facet_scales = "free_y")
# --- split_by ---
LollipopPlot(mtcars, x = "qsec", y = "drat", size_by = "wt",
split_by = "vs", palette = list("0" = "Reds", "1" = "Blues"))
# --- Border customization ---
LollipopPlot(mtcars, x = "qsec", y = "drat", size_by = "wt",
fill_by = "mpg", border_color = "red", border_size = 2)
LollipopPlot(mtcars, x = "qsec", y = "drat", size_by = "wt",
fill_by = "mpg", border_color = TRUE, border_size = 1.5,
border_alpha = 0.5)
LollipopPlot(mtcars, x = "qsec", y = "drat",
fill_by = "mpg", border_color = FALSE)
Atomic dot/lollipop plot
Description
Core implementation for dot plots and lollipop plots. This is the internal
workhorse dispatched by both DotPlot() and LollipopPlot(). It
renders a matrix of points where dot size encodes one variable and dot fill
colour encodes another, with optional background stripes and a lollipop
(bar + dot) display mode.
Usage
DotPlotAtomic(
data,
x,
y,
x_sep = "_",
y_sep = "_",
flip = FALSE,
lollipop = FALSE,
size_by = NULL,
fill_by = NULL,
fill_cutoff = NULL,
palreverse = FALSE,
size_name = NULL,
fill_name = NULL,
fill_cutoff_name = NULL,
size_min = 1,
size_max = 10,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
alpha = 1,
border_color = "black",
border_size = 0.5,
border_alpha = 1,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
bg_direction = c("vertical", "horizontal", "v", "h"),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
...
)
Arguments
data |
A data frame. |
x |
A character vector specifying the column(s) to use for the x-axis.
Can be numeric (for scatter/lollipop mode) or factor/character (for dot
matrix mode). When multiple columns are provided for a non-numeric axis,
they are concatenated with |
y |
A character vector specifying the column(s) to use for the y-axis.
Can be numeric (for scatter mode) or factor/character (for dot matrix or
lollipop mode). When multiple columns are provided for a non-numeric axis,
they are concatenated with |
x_sep |
A character string used to join multiple |
y_sep |
A character string used to join multiple |
flip |
A logical value. If |
lollipop |
A logical value. If |
size_by |
A character string naming a numeric column whose values
control dot size. When |
fill_by |
A character string naming a numeric column whose values
control the fill colour of the dots (and lollipop inner bars). A
continuous gradient from |
fill_cutoff |
A string expression specifying which values of
|
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
size_name |
A character string for the size legend title. When
|
fill_name |
A character string for the fill colour-bar legend title.
When |
fill_cutoff_name |
A character string for the fill cutoff legend title
(shown when |
size_min |
A numeric value for the smallest dot size in the
|
size_max |
A numeric value for the largest dot size in the
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
border_color |
Controls the dot border colour and lollipop outer-shadow appearance:
|
border_size |
A numeric value for the stroke width of dot borders and
the base linewidth of lollipop bars. In lollipop mode, the outer shadow
uses |
border_alpha |
A numeric value in |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
add_bg |
A logical value. If |
bg_palette |
A character string specifying the palette for the
background stripe colours. Passed to |
bg_palcolor |
A character vector of colours for the background stripes.
Passed to |
bg_alpha |
A numeric value in |
bg_direction |
A character string specifying which axis receives the
alternating background stripes. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
... |
Additional arguments. |
Details
The function supports two display modes:
-
Dot plot (
lollipop = FALSE, the default) — rendersggplot2::geom_point()withshape = 21(filled circle). Either or both axes can be numeric (producing a scatter plot) or factor (producing a dot matrix). Dot size scales bysize_by(or the per-combination observation count whensize_byisNULL) viascale_size(range = c(size_min, size_max)). Dot fill follows thefill_bycolumn viascale_fill_gradientn(). -
Lollipop plot (
lollipop = TRUE) — expects a numericxand a factor/charactery. Renders a two-layer bar: an outer shadow segment followed by an inner coloured segment, each capped by a filled dot. The outer shadow is black (or a custom colour whenborder_coloris a string), and the inner segment + dot fill followfill_by.
When add_bg = TRUE, alternating background stripes are drawn via
bg_layer() along the discrete axis (vertical stripes for
factor x, horizontal stripes for factor y). The fill colour
scale is prepared via prepare_continuous_color_scale() and
can be trimmed with lower_quantile/upper_quantile or
lower_cutoff/upper_cutoff.
When fill_cutoff is set (e.g. "< 18"), values of
fill_by matching the condition are set to NA and rendered in
grey ("grey80"), with a separate legend entry documenting the cutoff.
Border colour modes:
-
border_color = TRUE— dot borders and lollipop inner bar colour track thefill_bygradient viascale_color_gradientn(); lollipop outer shadow is black. -
border_color = "black"(default) — constant black borders on dots and a black outer shadow on lollipop bars. -
border_color = FALSE— no dot borders, no lollipop outer shadow (the inner coloured segment remains).
Value
A ggplot object with height and width
attributes.
Architecture
DotPlotAtomic executes the following steps:
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
bg_direction normalisation —
match.arg()resolves"v"/"h"abbreviations to"vertical"/"horizontal". -
Axis type detection — determines whether
x(resp.y) is numeric by checking that the column is a single name and the data column is neither character nor factor. -
Column resolution — non-numeric x and y are processed via
check_columns()withforce_factor = TRUE, allow_multi = TRUE, concat_multi = TRUEusingx_sep/y_sep.fill_byandfacet_byare also validated. -
NA / empty handling —
process_keep_na_empty()filters data and extractskeep_emptysettings for x, y, and facet_by. -
Multi-facet keep_empty guard — when
facet_byhas more than one column, thekeep_emptyvalues must be identical for all facet columns (consistent drop behaviour). -
fill_cutoff guard — errors if
fill_cutoffis set butfill_byisNULL. -
Size-by resolution — when
size_by = NULL:Groups data by the unique combination of x, y, and facet_by columns and counts rows per combination into
.size.If
fill_byis present,summarise()also takes the first value offill_byper group (with a warning that only the first value is used).Factor levels of x, y, and facet_by are preserved post-summary.
Sets
size_by <- ".size".
-
fill_cutoff parsing — if
fill_cutoffis set:Numeric shorthand (e.g.
18) is converted to"< 18".The string is parsed with regex
^(<=?|>=?)\\s*(-?[0-9.]+)$to extract operator and numeric threshold.A
switch()on the operator NAs-out matching values infill_by(e.g."<"sets values below the threshold toNA).A label
"<fill_by> <fill_cutoff>"is generated for the legend.
-
Default fill_by — when
fill_by = NULL, a synthetic.fill_bycolumn (constant1) is created and the fill legend is suppressed. -
Continuous colour scale preparation — when
fill_byis numeric,prepare_continuous_color_scale()computesfeat_colors_value(the range endpoints after optional quantile trimming or cutoff clamping). -
Base ggplot — initialises
ggplot(data, aes(x, y)). -
Background layer — if
add_bg = TRUE:Vertical stripes (
bg_direction = "vertical") require a non-numeric x-axis; horizontal stripes require a non-numeric y-axis.Calls
bg_layer()with the relevant discrete column and stripe styling.
-
Discrete axis scales —
scale_x_discrete()/scale_y_discrete()withdrop = !isTRUE(keep_empty_*)for non-numeric axes. -
Lollipop branch (
lollipop = TRUE):Sets x-axis expansion to
c(0, 0, 0.05, 0)(bars start at x = 0 with a 5\-
Outer shadow —
geom_segment()from x = 0 to the data value, coloured black (orborder_colorwhen a string), with linewidthborder_size * 4. Skipped whenborder_color = FALSE. -
Inner coloured bar —
geom_segment()mapped to thefill_bygradient viascale_color_gradientn(), with linewidthborder_size * 2. -
ggnewscale::new_scale_color()resets the colour scale for the subsequent point layer.
-
Point layer —
geom_point(shape = 21)(filled circle with border) with four dispatch paths:-
Numeric size + gradient border:
aes(fill, color)both mapped tofill_by;size = size_byconstant. -
Numeric size + constant/no border:
aes(fill, color = "")with a constant colour string. -
Column size + gradient border:
aes(size, fill, color)withscale_size(range = c(size_min, size_max))and a size legend (title =size_name, order = 1). -
Column size + constant/no border:
aes(size, fill, color = "")with the same size scale.
-
-
Fill scale —
scale_fill_gradientn()withpalette_this(),feat_colors_valuefor rescaled colour mapping,na.value = "grey80", and a colour-bar legend (title =fill_name, order = 2) orguide_none()when nofill_bywas provided. -
Labels —
labs(title, subtitle, x, y)with fallback to column names via%||%. -
Theme —
do_call(theme, theme_args)pluspanel.grid.major(grey80 dashed) and rotated x-axis text viacalc_just(x_text_angle). -
Colour (border) scale:
-
border_color = TRUE—scale_color_gradientn()following thefill_bygradient (with border_alpha), guide suppressed (the fill colour-bar serves both). -
border_color = FALSE—scale_color_manual()with"transparent", guide suppressed. Constant string —
scale_color_manual()with the alpha-adjusted colour, guide suppressed.
-
-
fill_cutoff legend — when
fill_cutoffis active and there are NA values infill_by, aguide_legend()(order = 3) is added showing the cutoff label with a grey fill and the border colour. -
Flip — optional
coord_flip()swaps x and y axes. -
Dimension calculation —
calculate_plot_dimensions()withbase_height = 4.5,aspect.ratio = NULL, and per-axis scale factors (0.9 for the categorical axis driving width, 0.6 for the categorical axis driving height). Legend width, y-axis label length, and minimum dimensions (width\ge5, height\ge4) are factored in. A fallback manual calculation is used whencalculate_plot_dimensions()returnsNULL. -
Faceting —
facet_plot()appliesfacet_grid/facet_wrapwithdrop = !isTRUE(keep_empty_facet).
Enrichment Map and Enrichment Network
Description
EnrichMap draws an enrichment map – a gene-set similarity network
where each node is an enriched term, node size encodes the number of
associated genes, node fill colour encodes cluster membership (detected
via igraph community detection), and edge thickness encodes the number
of overlapping genes between term pairs. The plot uses a force-directed
layout to arrange terms, and ggforce hull annotations group terms into
clusters. Keyword or term-description labels appear in the legend.
EnrichNetwork draws an enrichment network – a term-gene bipartite
graph where term nodes are shown as numbered circles and gene nodes as
labelled rectangles. Gene node colours are blended from the colours of
all terms they belong to. A force-directed layout positions the nodes,
with optional overlap adjustment for better readability.
Both functions accept enrichment results from clusterProfiler or Enrichr
(the latter is auto-detected and preprocessed via
prepare_enrichr_result()).
Usage
EnrichMap(
data,
in_form = c("auto", "clusterProfiler", "clusterprofiler", "enrichr"),
split_by = NULL,
split_by_sep = "_",
top_term = 10,
metric = "p.adjust",
layout = "fr",
minchar = 2,
cluster = "fast_greedy",
show_keyword = FALSE,
nlabel = 4,
character_width = 50,
mark = "ellipse",
label = c("term", "feature"),
labelsize = 5,
expand = c(0.4, 0.4),
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
EnrichNetwork(
data,
in_form = c("auto", "clusterProfiler", "clusterprofiler", "enrichr"),
split_by = NULL,
split_by_sep = "_",
top_term = 10,
metric = "p.adjust",
character_width = 50,
layout = "fr",
layoutadjust = TRUE,
adjscale = 60,
adjiter = 100,
blendmode = "blend",
labelsize = 5,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame containing enrichment results in clusterProfiler
format (see |
in_form |
A character string specifying the input format.
When |
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
top_term |
An integer specifying the maximum number of terms to
include. Terms are ranked by |
metric |
A character string specifying the significance metric
used for top-term selection and node scoring: |
layout |
A character string naming the igraph layout algorithm.
Built-in shortcuts: |
minchar |
An integer specifying the minimum character length for
words to be included as keywords when |
cluster |
A character string naming the igraph community detection
algorithm. The suffix passed to |
show_keyword |
A logical value. When |
nlabel |
An integer specifying the number of keywords or term
descriptions to show per cluster in the legend labels. Default
|
character_width |
An integer specifying the maximum width (in
characters) at which keyword labels are wrapped via
|
mark |
A character string naming the ggforce hull function.
One of |
label |
A character string specifying what information to display
in the legend labels. Either |
labelsize |
A numeric value specifying the font size of the
cluster labels drawn by the ggforce mark layer. Default |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
The random seed to use. Default is 8525. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments. |
layoutadjust |
A logical value. When |
adjscale |
A numeric value controlling the scale of the layout
adjustment. Passed as the |
adjiter |
A numeric value controlling the number of iterations for
the layout adjustment. Passed as the |
blendmode |
A character string specifying how gene colours are
computed from the colours of the terms they belong to. One of
|
Value
A ggplot object (single plot), a patchwork /
wrap_plots object (when split_by is provided and
combine = TRUE), or a list of ggplot objects (when
split_by is provided and combine = FALSE).
A ggplot object (single plot), a patchwork /
wrap_plots object (when split_by is provided and
combine = TRUE), or a list of ggplot objects (when
split_by is provided and combine = FALSE).
split_by Workflow (EnrichMap)
When split_by is provided, EnrichMap() executes the
following pipeline:
-
Argument validation –
validate_common_args()checks the seed. -
Input format detection –
match.arg()resolvesin_form;"auto"mode infers the format from column names. -
Enrichr preprocessing – when format is
"enrichr", callsprepare_enrichr_result()to rename columns and infer GeneRatio/BgRatio. -
Split column resolution –
check_columns()validatessplit_by(force_factor, allow_multi, concat_multi). -
Data splitting – splits
databysplit_bylevels, preserving factor level order. -
Per-split palette/colour –
check_palette()andcheck_palcolor()resolve per-split palette and colour overrides. -
Per-split legend –
check_legend()resolveslegend.positionandlegend.directionper split. -
Per-split title – when
titleis a function, it receives the default title (the split level name); otherwisetitle %||% split_levelis used. -
Dispatch – each split subset is passed to
EnrichMapAtomicwith its resolved parameters. -
Combination –
combine_plots()assembles the list of plots viapatchwork::wrap_plots, honouringnrow/ncol/byrow/axes/axis_titles/guides/design.
split_by Workflow (EnrichNetwork)
When split_by is provided, EnrichNetwork() executes the
same pipeline as EnrichMap() above, but dispatches each split
subset to EnrichNetworkAtomic.
Examples
data(enrich_example)
EnrichMap(enrich_example)
EnrichMap(enrich_example, label = "feature")
EnrichMap(enrich_example, show_keyword = TRUE, label = "term")
EnrichMap(enrich_example, show_keyword = TRUE, label = "feature")
data(enrich_multidb_example)
EnrichMap(enrich_multidb_example, split_by = "Database")
EnrichMap(enrich_multidb_example, split_by = "Database",
palette = list(DB1 = "Paired", DB2 = "Set1"))
EnrichNetwork(enrich_example, top_term = 5)
Atomic enrichment map (internal)
Description
Core implementation for drawing a single enrichment map – a gene-set
similarity network where nodes represent enriched terms, node fill colour
encodes cluster membership, node size encodes the number of genes per
term, and edge thickness encodes the number of overlapping genes between
pairs of terms. This is the workhorse behind the exported
EnrichMap function – it takes a single data frame (no
split_by support) and returns a ggplot object.
The function constructs an undirected graph from the term-term gene overlap matrix, computes a force-directed layout, detects term clusters via igraph community detection, and renders the result as a labelled network plot with ggforce hull annotations around each cluster.
Usage
EnrichMapAtomic(
data,
in_form = "clusterProfiler",
top_term = 100,
metric = "p.adjust",
layout = "fr",
minchar = 2,
cluster = "fast_greedy",
show_keyword = FALSE,
nlabel = 4,
character_width = 50,
words_excluded = plotthis::words_excluded,
mark = "ellipse",
label = c("term", "feature"),
labelsize = 5,
expand = c(0.4, 0.4),
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
...
)
Arguments
data |
A data frame containing enrichment results in clusterProfiler
format with at least the columns:
|
in_form |
A character string specifying the input format.
When |
top_term |
An integer specifying the maximum number of terms to
include. Terms are ranked by |
metric |
A character string specifying the significance metric
used for top-term selection and node scoring: |
layout |
A character string naming the igraph layout algorithm.
Built-in shortcuts: |
minchar |
An integer specifying the minimum character length for
words to be included as keywords when |
cluster |
A character string naming the igraph community detection
algorithm. The suffix passed to |
show_keyword |
A logical value. When |
nlabel |
An integer specifying the number of keywords or term
descriptions to show per cluster in the legend labels. Default
|
character_width |
An integer specifying the maximum width (in
characters) at which keyword labels are wrapped via
|
words_excluded |
A character vector of words to exclude from
keyword extraction when |
mark |
A character string naming the ggforce hull function.
One of |
label |
A character string specifying what information to display
in the legend labels. Either |
labelsize |
A numeric value specifying the font size of the
cluster labels drawn by the ggforce mark layer. Default |
expand |
A numeric vector of length 2 (or 4) specifying the
expansion of the x and y axes, processed via
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch – selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Data format conversion – if
datainherits from"enrichResult", converts viaas.data.frame(); ifin_form == "enrichr", callsprepare_enrichr_result()to rename columns and infer GeneRatio/BgRatio. -
Column validation –
check_columns()verifies thatDescription,GeneRatio,pvalue,p.adjust, andgeneIDare present. -
Top-term selection – when
top_termis notNULL, selects the top N terms by the chosenmetricviadplyr::slice_min(). -
Metric transformation – computes
-\log_{10}(metric)as the node scoring variable. SplitsgeneIDon"/"to obtain per-term gene lists. -
ID assignment – uses the
IDcolumn if present; otherwise falls back to row names or generates synthetic IDs ("GS1","GS2", ...). -
Edge construction – creates all pairwise combinations (
utils::combn()) of term IDs and computes the overlap count (intersection of geneID elements) as edge weight. Edges with weight 0 are dropped. -
igraph graph construction –
igraph::graph_from_data_frame()builds an undirected graph from the edge list, with node attributes from the term data. -
Layout computation – dispatches to the chosen igraph layout function (
layout_with_*) or one of the built-in shortcuts ("circle","tree","grid"). -
Cluster detection – runs the chosen igraph clustering algorithm (
cluster_*) to group related terms into modules. -
Node coordinates – extracts vertex positions and cluster assignments into a data frame with
dim1,dim2, andclusterscolumns. -
Keyword extraction – when
show_keyword = TRUE, tokenizesDescriptiontext, filters words bymincharandwords_excluded, scores remaining words by summedmetricper cluster, and keeps the topnlabelkeywords. Otherwise, the termDescriptiontexts themselves are used as keywords. -
Gene keyword extraction – always computes per-cluster gene-level keywords (top
nlabelgenes by summedmetric) for the feature legend mode. -
Mark layer –
ggforce::geom_mark_*()(ellipse, rect, circle, or text) draws cluster hulls with labels containing the cluster ID and either term or feature keywords. -
Edge rendering –
ggplot2::geom_segment()draws edges with line width proportional to overlap weight. -
Node rendering –
ggplot2::geom_point(shape = 21)draws nodes sized byCountand filled by cluster membership. -
Scale configuration –
scale_size()for node size,scale_linewidth()for edge width,scale_fill_manual()for cluster colours with custom legend labels (term keywords or gene keywords depending onlabel). -
Theme and dimensions – applies the resolved theme, sets aspect ratio and legend position, then calls
calculate_plot_dimensions()to attachheight/widthattributes.
Atomic enrichment network (internal)
Description
Core implementation for drawing a single enrichment network – a
term-gene bipartite graph where enriched terms and their member genes
are shown as interconnected nodes. Term nodes are displayed as numbered
filled circles with a colour-coded legend; gene nodes are displayed as
labelled rectangles coloured by a blend of the term colours they belong
to. This is the workhorse behind the exported EnrichNetwork
function – it takes a single data frame (no split_by support)
and returns a ggplot object.
The function constructs a bipartite graph between terms and genes, computes a force-directed layout, optionally adjusts node positions to reduce overlap, blends term colours for shared genes, and renders the result as a labelled network.
Usage
EnrichNetworkAtomic(
data,
top_term = 6,
metric = "p.adjust",
character_width = 50,
layout = "fr",
layoutadjust = TRUE,
adjscale = 60,
adjiter = 100,
blendmode = "blend",
labelsize = 5,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
...
)
Arguments
data |
A data frame containing enrichment results in clusterProfiler
format (see |
top_term |
An integer specifying the maximum number of terms to
include. Terms are ranked by |
metric |
A character string specifying the significance metric for
top-term selection: |
character_width |
An integer specifying the maximum width (in
characters) at which term descriptions are wrapped via
|
layout |
A character string naming the igraph layout algorithm.
Built-in shortcuts: |
layoutadjust |
A logical value. When |
adjscale |
A numeric value controlling the scale of the layout
adjustment. Passed as the |
adjiter |
A numeric value controlling the number of iterations for
the layout adjustment. Passed as the |
blendmode |
A character string specifying how gene colours are
computed from the colours of the terms they belong to. One of
|
labelsize |
A numeric value specifying the font size of the
numeric term labels displayed via |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch – selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Data format conversion – if
datainherits from"enrichResult", converts viaas.data.frame(). -
Column validation –
check_columns()verifies thatDescription,GeneRatio,pvalue,p.adjust, andgeneIDare present. -
Top-term selection – when
top_termis notNULL, selects the top N terms bymetricviadplyr::slice_min(). -
Metric and description preparation – computes
-\log_{10}(metric)as the scoring variable. WrapsDescriptiontext tocharacter_widthand parsesgeneIDby splitting on"/". -
Gene-term unnesting – unnests the
geneIDcolumn to produce a gene-term mapping table. -
Bipartite node construction – creates nodes for both terms (
class = "term") and genes (class = "gene"), carrying theDatabaseattribute if present. -
Bipartite edge construction – edges connect each term to its member genes with uniform weight (
weight = 1). -
igraph graph construction –
igraph::graph_from_data_frame()builds an undirected bipartite graph. -
Layout computation – dispatches to the chosen igraph layout function (
layout_with_*) or built-in shortcuts ("circle","tree","grid"). -
Layout adjustment – when
layoutadjust = TRUE(default), callsadjust_network_layout()to push overlapping nodes apart based on label width and a repulsion simulation. -
Node coordinates – extracts vertex positions into
dim1anddim2columns. -
Colour computation – palette colours are assigned to term nodes. Gene node colours are computed by blending the colours of all connected terms via the specified
blendmodeusingblend_colors(). -
Label colour – each node's text colour is chosen as black or white based on the luminance of its fill colour (sum of RGB channels > 510).
-
Numeric labels – term nodes receive sequential integer labels; gene nodes display their gene symbol.
-
Custom legend key –
draw_key_cust()renders term legend entries as numbered circles viaggrepel::shadowtextGrob(). -
Edge rendering –
ggplot2::geom_segment()draws edges coloured by the source term (legend suppressed). -
Gene node rendering –
ggplot2::geom_label()displays gene symbols with fill colour blended from connected terms. -
Term node rendering – two
geom_point()layers draw black-outlined circles filled with the term colour, withdraw_key_custas the key glyph. -
Term labels –
ggrepel::geom_text_repel()places the numeric term labels with white text on a black background. -
Scale configuration –
scale_color_identity()andscale_fill_identity()with a manual legend mapping term colours to term descriptions. -
Theme and dimensions – applies the resolved theme, sets aspect ratio and legend position, then calls
calculate_plot_dimensions()to attachheight/widthattributes.
Atomic GSEA plot (internal)
Description
Core implementation for drawing a single GSEA (Gene Set Enrichment Analysis)
ridge plot. This is the workhorse behind the exported GSEAPlot
function — it takes a single gene set and produces a three-panel figure
showing the running enrichment score, hit positions, and the ranked list
metric.
The plot consists of three vertically stacked panels:
-
Running score panel — traces the running enrichment score across the ranked gene list, with a peak annotation and optional gene labels for core enrichment genes.
-
Hit indicator panel — marks the positions of gene set members with vertical lines, colour-coded by the rank metric value (red for positive, blue for negative).
-
Gene ranking panel — shows every gene's rank as a vertical segment, with annotations indicating positively and negatively correlated tails and the zero-crossing point.
The running enrichment score is computed via gsea_running_score()
using the gene_ranks and genes provided. Core enrichment genes
(from the core_enrichment column) can be labelled on the score panel
using geom_text_repel().
Usage
GSEAPlotAtomic(
data,
gene_ranks = "@gene_ranks",
gs,
genes,
metric = "p.adjust",
sample_coregenes = FALSE,
line_width = 1.5,
line_alpha = 1,
line_color = "#6BB82D",
n_coregenes = 10,
genes_label = NULL,
label_fg = "black",
label_bg = "white",
label_bg_r = 0.1,
label_size = 4,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
...
)
Arguments
data |
A data frame. |
gene_ranks |
A named numeric vector of gene-level rank statistics, with
gene identifiers as names. Used to calculate the running enrichment score
and the ranked list metric. If a character string starting with
|
gs |
Character string specifying the |
genes |
Character vector of gene identifiers belonging to the gene set.
These are intersected with |
metric |
Character string specifying the column name in |
sample_coregenes |
Logical; if |
line_width |
Numeric specifying the line width for the running
enrichment score curve. Default is |
line_alpha |
Numeric alpha transparency for the running score line and
hit indicator bars. Default is |
line_color |
Character string specifying the colour of the running
enrichment score line. Default is |
n_coregenes |
Integer specifying the number of core enrichment genes to
label on the running score plot. Default is |
genes_label |
Character vector of specific gene names to label on the
running score plot. When provided, |
label_fg |
Character string specifying the text colour of gene labels.
Default is |
label_bg |
Character string specifying the background colour of gene
labels. Default is |
label_bg_r |
Numeric specifying the corner radius of the label
background. Default is |
label_size |
Numeric specifying the font size of the label text.
Default is |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
Character string for a right-side y-axis label (rotated 90 degrees). When provided, an extra text grob is added to the right of the assembled plot, and the plot width increases from 7.5 to 8 inches. |
... |
Additional arguments. |
Value
A patchwork object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Data subsetting — if
datacontains multiple gene sets (nrow > 1), it is filtered to the single row matchinggs. An error is raised if no rows match. -
Gene rank resolution — resolves
gene_ranksfrom its"@"-prefixed attribute reference, validates that it is a named numeric vector, and sorts it in descending order. -
Title and subtitle construction —
titledefaults todata$Description.subtitleis built from the NES value and themetriccolumn with significance stars (ns/*/**/***/****). -
Plot data preparation — builds a data frame with position (1:N), gene names, running enrichment score (via
gsea_running_score()withhits_only = FALSE), raw ranks, and a hit indicator column. -
Running score panel — renders the top panel with a red/blue background (positive/negative score regions), a horizontal baseline at
y = 0, the running score line, and annotations for the peak (dashed reference lines and an upward/downward triangle). Title and subtitle are added viaggtitle(). -
Gene labeling — when
n_coregenes > 1orgenes_labelis provided, core enrichment genes are extracted fromdata$core_enrichmentand labelled on the running score panel usinggeom_text_repel(). Missing genes trigger a warning. -
Hit indicator panel — renders the middle panel: vertical lines (
geom_linerange) at each hit position, with coloured rectangles beneath showing the rank metric gradient (red for positive, blue for negative). -
Gene ranking panel — renders the bottom panel: vertical segments (
geom_segment) for every gene's rank, with annotations for positively/negatively correlated tails. If both signs exist, the zero-crossing point is marked with a dashed vertical line. -
Panel assembly — the three panels are stacked vertically via
wrap_plots()with spacer panels and proportional heights (3.5 / 1 / 1.5). Whenylabis provided, a rotatedtextGrob()is added to the right side and the plot width increases from 7.5 to 8 inches. -
Dimensions — height is fixed at 6.5 inches. Width is 7.5 inches (without
ylab) or 8 inches (withylab). Attributesheightandwidthare stored on the returned object.
GSEA summary dot plot
Description
Produces a summary dot plot of GSEA (Gene Set Enrichment Analysis) results.
Each row represents a gene set (term), positioned along the x-axis by its
Normalized Enrichment Score (NES). Dot colour encodes the significance level
(typically -log10(p.adjust)) on a continuous gradient, and each row
includes a miniature line plot showing the gene ranks or running enrichment
score for that term's gene set.
The function supports both DOSE and fgsea package output
formats via the in_form parameter. Terms can be ranked and selected
by a significance metric (top_term, metric), with
non-significant terms rendered in grey. The per-term line plots can show
either the raw preranked gene statistics (line_by = "prerank") or
the running enrichment score (line_by = "running_score").
Usage
GSEASummaryPlot(
data,
in_form = c("auto", "dose", "fgsea"),
gene_ranks = "@gene_ranks",
gene_sets = "@gene_sets",
top_term = 10,
metric = "p.adjust",
cutoff = 0.05,
character_width = 50,
line_plot_size = 0.25,
metric_name = metric,
nonsig_name = "Insignificant",
linewidth = 0.2,
line_by = c("prerank", "running_score"),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
alpha = 0.6,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
seed = 8525,
...
)
GSEAPlot(
data,
in_form = c("auto", "dose", "fgsea"),
gene_ranks = "@gene_ranks",
gene_sets = "@gene_sets",
gs = NULL,
sample_coregenes = FALSE,
line_width = 1.5,
line_alpha = 1,
line_color = "#6BB82D",
n_coregenes = 10,
genes_label = NULL,
label_fg = "black",
label_bg = "white",
label_bg_r = 0.1,
label_size = 4,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
in_form |
The format of the input data. See |
gene_ranks |
A named numeric vector of gene-level rank statistics, with
gene identifiers as names. Used to construct the per-term line plots.
If a character string starting with |
gene_sets |
A named list of gene sets. Each name must correspond to an
|
top_term |
Integer specifying the number of top terms to display, ranked
by |
metric |
Character string specifying the column name used to rank terms
and assess significance. Typically |
cutoff |
Numeric threshold for the |
character_width |
Integer specifying the maximum character width for
wrapping term descriptions on the y-axis. Default is |
line_plot_size |
Numeric controlling the size of the per-term miniature
enrichment plots embedded in each row. Expressed as a fraction of the plot
panel dimensions. Default is |
metric_name |
Character string for the colour bar legend title.
Defaults to the value of |
nonsig_name |
Character string for the legend entry label used for
non-significant terms. Default is |
linewidth |
Numeric specifying the line width within the per-term
miniature enrichment plots. Default is |
line_by |
The method used to compute the per-term line plots:
|
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
seed |
A numeric seed for reproducibility. Passed to
|
... |
Additional arguments. |
gs |
Character vector of gene set |
sample_coregenes |
Logical; if |
line_width |
Numeric specifying the line width for the running
enrichment score curve. Default is |
line_alpha |
Numeric alpha transparency for the running score line and
hit indicator bars. Default is |
line_color |
Character string specifying the colour of the running
enrichment score line. Default is |
n_coregenes |
Integer specifying the number of core enrichment genes to
label on the running score plot. Default is |
genes_label |
Character vector of specific gene names to label on the
running score plot. When provided, |
label_fg |
Character string specifying the text colour of gene labels.
Default is |
label_bg |
Character string specifying the background colour of gene
labels. Default is |
label_bg_r |
Numeric specifying the corner radius of the label
background. Default is |
label_size |
Numeric specifying the font size of the label text.
Default is |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default |
axes |
A character string specifying how axes should be treated across
the combined layout (passed to |
axis_titles |
A character string specifying how axis titles should be
treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should be
collected across panels (passed to |
design |
A custom layout design for the combined plot (passed to
|
Value
A ggplot object with height and width
attributes (in inches) attached.
A patchwork object when combine = TRUE, or a named
list of patchwork objects when combine = FALSE. Each
individual plot has height and width attributes in inches.
Examples
data(gsea_example)
# Default summary dot plot with preranked gene statistics
GSEASummaryPlot(gsea_example)
# Use running enrichment score for per-term line plots
GSEASummaryPlot(gsea_example, line_by = "running_score")
# Raise the significance cutoff (all terms are coloured)
GSEASummaryPlot(gsea_example, cutoff = 0.01)
data(gsea_example)
# Single gene set
GSEAPlot(gsea_example, gene_sets = attr(gsea_example, "gene_sets")[1])
# Multiple gene sets arranged in a grid
GSEAPlot(gsea_example, gene_sets = attr(gsea_example, "gene_sets")[1:4])
Heatmap
Description
Draw a heatmap to visualise data in matrix form. This is the public,
exported interface — it accepts data in multiple input formats (matrix,
wide, or long), preprocesses it via process_heatmap_data,
and delegates to HeatmapAtomic for rendering. Commonly
used in biology to visualise gene expression, but applicable to any
matrix-structured data.
Usage
Heatmap(
data,
values_by = NULL,
values_fill = NA,
name = NULL,
in_form = c("auto", "matrix", "wide-columns", "wide-rows", "long"),
split_by = NULL,
split_by_sep = "_",
rows_by = NULL,
rows_by_sep = "_",
rows_split_by = NULL,
rows_split_by_sep = "_",
columns_by = NULL,
columns_by_sep = "_",
columns_split_by = NULL,
columns_split_by_sep = "_",
rows_data = NULL,
columns_data = NULL,
keep_na = FALSE,
keep_empty = FALSE,
rows_orderby = NULL,
columns_orderby = NULL,
columns_name = NULL,
columns_split_name = NULL,
rows_name = NULL,
rows_split_name = NULL,
palette = "RdBu",
palcolor = NULL,
palreverse = FALSE,
pie_size_name = "size",
pie_size = NULL,
pie_values = "length",
pie_name = NULL,
pie_group_by = NULL,
pie_group_by_sep = "_",
pie_palette = "Spectral",
pie_palcolor = NULL,
bars_sample = 100,
label = identity,
label_size = 10,
label_color = "black",
label_name = "label",
mark = identity,
mark_color = "black",
mark_size = 1,
mark_name = "mark",
violin_fill = NULL,
boxplot_fill = NULL,
dot_size = 8,
dot_size_name = "size",
legend_items = NULL,
legend_discrete = FALSE,
legend.position = "right",
legend.direction = "vertical",
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
add_bg = FALSE,
bg_alpha = 0.5,
add_reticle = FALSE,
reticle_color = "grey",
cluster_columns = NULL,
cluster_rows = NULL,
show_row_names = NULL,
show_column_names = NULL,
border = TRUE,
title = NULL,
column_title = NULL,
row_title = NULL,
na_col = "grey85",
row_names_side = "right",
column_names_side = "bottom",
row_annotation = NULL,
row_annotation_side = NULL,
row_annotation_palette = NULL,
row_annotation_palcolor = NULL,
row_annotation_type = NULL,
row_annotation_params = NULL,
row_annotation_agg = NULL,
column_annotation = NULL,
column_annotation_side = NULL,
column_annotation_palette = NULL,
column_annotation_palcolor = NULL,
column_annotation_type = NULL,
column_annotation_params = NULL,
column_annotation_agg = NULL,
flip = FALSE,
alpha = 1,
seed = 8525,
padding = 15,
base_size = 1,
aspect.ratio = NULL,
draw_opts = list(),
layer_fun_callback = NULL,
cell_type = c("tile", "bars", "label", "mark", "label+mark", "mark+label", "dot",
"violin", "boxplot", "pie"),
cell_agg = NULL,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame or matrix. When a matrix, it is melted to long format internally (requires row and column names). |
values_by |
A character of column name in |
values_fill |
A value used to fill missing cells in the matrix.
Default |
name |
A character string to name the heatmap (will be used to rename |
in_form |
The format of the data. Can be one of |
split_by |
A character of column name in |
split_by_sep |
A character string to concat multiple columns in |
rows_by |
A vector of column names in |
rows_by_sep |
A character string to concat multiple columns in |
rows_split_by |
A character of column name in |
rows_split_by_sep |
A character string to concat multiple columns in |
columns_by |
A vector of column names in |
columns_by_sep |
A character string to concat multiple columns in |
columns_split_by |
A character of column name in |
columns_split_by_sep |
A character string to concat multiple columns in |
rows_data |
A data frame containing additional data for rows, which can be used to add annotations to the heatmap.
It will be joined to the main data by |
columns_data |
A data frame containing additional data for columns, which can be used to add annotations to the heatmap.
It will be joined to the main data by |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
rows_orderby |
A expression (in character) to specify how to order rows. It will be evaluated in the context of the data frame used for rows (after grouping by rows_split_by and rows_by). The expression should return a vector of the same length as the number of rows in the data frame. The default is NULL, which means no specific ordering. Can't be used with cluster_rows = TRUE. This is applied before renaming rows_by to rows_name. |
columns_orderby |
A expression (in character) to specify how to order columns. It will be evaluated in the context of the data frame used for columns (after grouping by columns split_by and columns_by). The expression should return a vector of the same length as the number of rows in the data frame. The default is NULL, which means no specific ordering. Can't be used with cluster_columns = TRUE. This is applied before renaming columns_by to columns_name. |
columns_name |
A character string to rename the column created by |
columns_split_name |
A character string to rename the column created by |
rows_name |
A character string to rename the column created by |
rows_split_name |
A character string to rename the column created by |
palette |
A character string naming a palette (see
|
palcolor |
A custom colour vector overriding |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
pie_size_name |
Legend title for the pie size. |
pie_size |
A numeric value or function returning the pie radius. When a function, it receives the count of groups in the pie. |
pie_values |
A function or string (convertible via
|
pie_name |
A character string to rename the column created by |
pie_group_by |
A character of column name in |
pie_group_by_sep |
A character string to concat multiple columns in |
pie_palette, pie_palcolor |
Palette and custom colours for pie slice fill colours. |
bars_sample |
Number of observations sampled per cell when
|
label |
A function to compute text labels when
|
label_size |
Default point size for label text (used as fallback
when the |
label_color |
Default colour for label text (fallback). |
label_name |
Legend title for the label colour scale. The legend
is shown automatically when the |
mark |
A function to compute mark symbols when
|
mark_color |
Default mark colour (fallback). |
mark_size |
Default mark stroke width ( |
mark_name |
Legend title for the mark colour scale. |
violin_fill |
A character vector of colours to use as fill for
violin plots when |
boxplot_fill |
A character vector of colours to use as fill for
boxplots when |
dot_size |
Dot size when |
dot_size_name |
Legend title for the dot size. |
legend_items |
A named numeric vector specifying custom legend entries for the main colour scale. Names become the displayed labels. |
legend_discrete |
Logical; if |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
lower_quantile, upper_quantile, lower_cutoff, upper_cutoff |
Quantile or explicit cutoffs for clipping the colour scale. Applied
to aggregated values for |
add_bg |
Logical; if |
bg_alpha |
Numeric in |
add_reticle |
Logical; if |
reticle_color |
Colour for the reticle lines. |
cluster_columns |
Logical; cluster the columns. If |
cluster_rows |
Logical; cluster the rows. If |
show_row_names |
Logical; show row names. If |
show_column_names |
Logical; show column names. If |
border |
A logical value indicating whether to draw borders around
the heatmap. If |
title |
The global (column) title of the heatmap. |
column_title |
Character string/vector used as the column group annotation title. |
row_title |
Character string/vector used as the row group annotation title. |
na_col |
Colour for |
row_names_side |
Side for row names. Default |
column_names_side |
Side for column names. Default |
row_annotation |
A structured list specifying row annotations.
Same format as |
row_annotation_side |
Deprecated: use
|
row_annotation_palette |
Deprecated: use
|
row_annotation_palcolor |
Deprecated: use
|
row_annotation_type |
Deprecated: use
|
row_annotation_params |
Deprecated: use
|
row_annotation_agg |
Deprecated: use
|
column_annotation |
A structured list specifying column annotations. Each entry is a named list with sub-keys:
Shortcuts:
Special keys:
|
column_annotation_side |
Deprecated: use
|
column_annotation_palette |
Deprecated: use
|
column_annotation_palcolor |
Deprecated: use
|
column_annotation_type |
Deprecated: use
|
column_annotation_params |
Deprecated: use
|
column_annotation_agg |
Deprecated: use
|
flip |
Logical; if |
alpha |
Alpha transparency for heatmap cells in |
seed |
The random seed to use. Default is 8525. |
padding |
Padding around the heatmap in CSS order (top, right,
bottom, left). Supports 1–4 values. Default 15 (mm). Note that
this is different from |
base_size |
A positive numeric scalar used as a scaling factor for the overall heatmap size. Default 1 (no scaling). Values > 1 enlarge all cell dimensions proportionally. |
aspect.ratio |
Height-to-width ratio of a single heatmap cell.
When |
draw_opts |
A named list of additional arguments passed to
|
layer_fun_callback |
A function to add custom graphical layers on
top of each heatmap cell. Receives |
cell_type |
The type of cell to render. One of |
cell_agg |
A function to aggregate values within each cell when
|
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments passed to
|
Value
A patchwork object (class wrap_plots) with
height and width attributes (in inches). When
combine = FALSE, a named list of such objects, one per
split_by level.
Input formats
The in_form parameter controls how the input data is
interpreted:
-
"auto"(default) — detects the format automatically. -
"matrix"—datais a matrix with row and column names. It is melted to long form internally. -
"wide-rows"— each row is a feature, columns are samples. -
"wide-columns"— each column is a feature, rows are samples. -
"long"— tidy/long format with one observation per row.
Split-by support
When split_by is provided, the data is partitioned into subsets
and an independent heatmap is produced for each level. Results are
combined via wrap_plots according to
nrow, ncol, byrow, and design. Per-split
palette, palcolor, legend.position, and
legend.direction can be specified as named lists keyed by split
level.
See Also
HeatmapAtomic, LinkedHeatmap,
anno_simple, anno_points,
anno_lines, anno_pie,
anno_violin, anno_boxplot,
anno_density
Examples
set.seed(8525)
matrix_data <- matrix(rnorm(60), nrow = 6, ncol = 10)
rownames(matrix_data) <- paste0("R", 1:6)
colnames(matrix_data) <- paste0("C", 1:10)
if (requireNamespace("cluster", quietly = TRUE)) {
Heatmap(matrix_data)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# use a different color palette
# change the main legend title
# show row names (legend will be hidden)
# show column names
# change the row name annotation name and side
# change the column name annotation name
Heatmap(matrix_data, palette = "viridis", values_by = "z-score",
show_row_names = TRUE, show_column_names = TRUE,
rows_name = "Features", row_names_side = "left",
columns_name = "Samples")
}
if (requireNamespace("cluster", quietly = TRUE)) {
# flip the heatmap
Heatmap(matrix_data, palette = "viridis", values_by = "z-score",
show_row_names = TRUE, show_column_names = TRUE,
rows_name = "Features", row_names_side = "left",
columns_name = "Samples", flip = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# add annotations to the heatmap
rows_data <- data.frame(
rows = paste0("R", 1:6),
group = sample(c("X", "Y", "Z"), 6, replace = TRUE)
)
Heatmap(matrix_data, rows_data = rows_data,
row_annotation = list(Group = list(col = "group", palette = "Spectral"))
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
Heatmap(matrix_data, rows_data = rows_data,
rows_split_by = "group"
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# use label annotation for split groups (shows group labels inside colored blocks)
Heatmap(matrix_data, rows_data = rows_data,
rows_split_by = "group",
row_annotation = list(.row.split = list(
type = "label",
params = list(
border = FALSE,
labels_gp = grid::gpar(col = "white", fontsize = 12),
labels_rot = 0
)
))
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# label annotation for column splits
columns_data <- data.frame(
columns = paste0("C", 1:10),
batch = rep(c("A", "B"), each = 5)
)
Heatmap(matrix_data, columns_data = columns_data,
columns_split_by = "batch",
column_annotation = list(.col.split = list(type = "label"))
)
}
rownames(matrix_data)[1] <- "R12345"
if (requireNamespace("cluster", quietly = TRUE)) {
# label annotation for name annotations: show row/column names as colored labels
Heatmap(matrix_data, rows_data = rows_data,
row_annotation = list(.row = list(
type = "label", palette = "Set2", side = "right",
params = list(labels_rot = 150)
)),
column_annotation = list(.col = list(
type = "label", params = list(labels_rot = 90)
))
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# add labels to the heatmap
Heatmap(matrix_data, rows_data = rows_data,
rows_split_by = "group", cell_type = "label",
base_size = 0.8,
label = function(x) ifelse(
x > 0, scales::number(x, accuracy = 0.01), NA
)
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# add labels based on an external data
pvalues <- matrix(runif(60, 0, 0.5), nrow = 6, ncol = 10)
Heatmap(matrix_data, rows_data = rows_data,
rows_split_by = "group", cell_type = "label",
base_size = 0.8,
label = function(x, i, j) {
pv <- ComplexHeatmap::pindex(pvalues, i, j)
ifelse(pv < 0.01, "***",
ifelse(pv < 0.05, "**",
ifelse(pv < 0.1, "*", NA)))
}
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# Set label color, size, legend and order
pvalues <- matrix(runif(60, 0, 0.5), nrow = 6, ncol = 10)
Heatmap(matrix_data, rows_data = rows_data,
rows_split_by = "group", cell_type = "label",
base_size = 0.6,
label_name = "Significance",
label = function(x, i, j) {
pv <- ComplexHeatmap::pindex(pvalues, i, j)
if (pv < 0.01)
list("***", color = "red", size = 12, legend = "p < 0.01", order = 1)
else if (pv < 0.05)
list("**", color = "orange", size = 10, legend = "p < 0.05", order = 3)
else if (pv < 0.1)
list("*", color = "yellow", size = 8, legend = "p < 0.1", order = 2)
else NA
}
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# add marks
Heatmap(matrix_data, rows_data = rows_data,
rows_split_by = "group", cell_type = "mark",
mark = function(x, i, j) {
pv <- ComplexHeatmap::pindex(pvalues, i, j)
if(pv < 0.01) list("[x]", legend = "p < 0.01")
else if (pv < 0.02) list("[o]", legend = "p < 0.02")
else if (pv < 0.03) list("[-]", legend = "p < 0.03")
else if (pv < 0.05) list("[()]", legend = "p < 0.05")
else if (pv < 0.06) list("+", legend = "p < 0.06")
else if (pv < 0.07) list("x", legend = "p < 0.07")
else if (pv < 0.08) list("[/]", legend = "p < 0.08")
else if (pv < 0.09) list("[\\]", legend = "p < 0.09")
else NA
}
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# add labels and marks
Heatmap(matrix_data, rows_data = rows_data,
rows_split_by = "group", cell_type = "mark+label",
label = scales::label_number(accuracy = 0.01),
mark = function(x, i, j) {
pv <- ComplexHeatmap::pindex(pvalues, i, j)
if(pv < 0.01) list("{}", legend = "p < 0.01")
else if(pv < 0.05) list("[]", legend = "p < 0.05")
else NA
},
mark_size = 1.5, mark_color = "red"
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# quickly simulate a GO board
go <- matrix(sample(c(0, 1, NA), 81, replace = TRUE), ncol = 9)
Heatmap(
go,
# Do not cluster rows and columns and hide the name annotations
# Use .row/.col aliases to disable the built-in name annotations
cluster_rows = FALSE, cluster_columns = FALSE,
row_annotation = list(.row = list(params = FALSE)),
column_annotation = list(.col = list(params = FALSE)),
show_row_names = FALSE, show_column_names = FALSE,
# Set the legend items
values_by = "Players", legend_discrete = TRUE,
legend_items = c("Player 1" = 0, "Player 2" = 1),
# Set the pawns
cell_type = "dot", dot_size = function(x) ifelse(is.na(x), 0, 10),
dot_size_name = NULL, # hide the dot size legend
palcolor = c("white", "black"),
# Set the board
add_reticle = TRUE,
# Set the size of the board
width = ggplot2::unit(105, "mm"), height = ggplot2::unit(105, "mm"))
}
if (requireNamespace("cluster", quietly = TRUE)) {
# Make the row/column name annotation thicker using the .row/.col aliases
Heatmap(matrix_data,
column_annotation = list(.col = list(params = list(height = 5))),
row_annotation = list(.row = list(params = list(width = 5))))
}
if (requireNamespace("cluster", quietly = TRUE)) {
# Per-annotation side control: row name annotation on the right,
# all other row annotations on the left (.default)
rows_data2 <- data.frame(
rows = sample(paste0("R", 1:6), 60, replace = TRUE),
group = sample(c("X", "Y"), 60, replace = TRUE),
score = runif(60)
)
Heatmap(matrix_data, rows_data = rows_data2,
rows_split_by = "group",
row_annotation = list(
.default = list(side = "left"),
.row = list(side = "right"),
Score = "score"
),
show_row_names = TRUE
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# Move all row annotations to the right side
Heatmap(matrix_data, rows_data = rows_data2,
rows_split_by = "group",
row_annotation = list(
.default = list(side = "right"),
Score = "score"
),
show_row_names = TRUE
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# Split and name annotations on opposite sides:
# split annotation on the default left, name annotation on the right
Heatmap(matrix_data, rows_data = rows_data2,
rows_split_by = "group",
row_annotation = list(
.default = list(side = "left"),
.row = list(side = "right")
),
show_row_names = TRUE
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# Row name label annotation on the right side (text rotated 90° clockwise)
Heatmap(matrix_data, rows_data = rows_data2,
row_annotation = list(.row = list(
type = "label", palette = "Set2", side = "right"
)),
show_row_names = TRUE
)
}
# Use long form data
N <- 500
data <- data.frame(
value = rnorm(N),
c = sample(letters[1:8], N, replace = TRUE),
r = sample(LETTERS[1:5], N, replace = TRUE),
p = sample(c("x", "y"), N, replace = TRUE),
q = sample(c("X", "Y", "Z"), N, replace = TRUE),
a = as.character(sample(1:5, N, replace = TRUE)),
p1 = runif(N),
p2 = runif(N)
)
if (requireNamespace("cluster", quietly = TRUE)) {
Heatmap(data, rows_by = "r", columns_by = "c", values_by = "value",
rows_split_by = "p", columns_split_by = "q", show_column_names = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# split into multiple heatmaps
Heatmap(data,
values_by = "value", columns_by = "c", rows_by = "r", split_by = "p",
upper_cutoff = 2, lower_cutoff = -2, legend.position = c("none", "right"),
design = "AAAAAA#BBBBBBB"
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# cell_type = "bars" (default is "tile")
Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
cell_type = "bars")
}
if (requireNamespace("cluster", quietly = TRUE)) {
p <- Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
cell_type = "dot", dot_size = length, dot_size_name = "data points",
add_bg = TRUE, add_reticle = TRUE)
p
}
if (requireNamespace("cluster", quietly = TRUE)) {
dot_size_data <- as.matrix(p$data)
# Make it big so we can see if we get the right indexing
# for dot_size function
dot_size_data["A", "a"] <- max(dot_size_data) * 2
Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
cell_type = "dot", dot_size_name = "data points",
dot_size = function(x, i, j) ComplexHeatmap::pindex(dot_size_data, i, j),
show_row_names = TRUE, show_column_names = TRUE,
add_bg = TRUE, add_reticle = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
cell_type = "pie", pie_group_by = "q", pie_size = sqrt,
add_bg = TRUE, add_reticle = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
cell_type = "violin", add_bg = TRUE, add_reticle = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
Heatmap(data, values_by = "value", rows_by = "r", columns_by = "c",
cell_type = "boxplot", add_bg = TRUE, add_reticle = TRUE)
}
if (requireNamespace("cluster", quietly = TRUE)) {
Heatmap(data,
values_by = "value", rows_by = "r", columns_by = "c",
column_annotation = list(
r1 = list(col = "p", type = "ring",
params = list(height = grid::unit(10, "mm"), show_legend = FALSE)),
r2 = list(col = "q", type = "bar"),
r3 = list(col = "p1", type = "violin",
params = list(height = grid::unit(18, "mm")))
),
row_annotation = list(
.default = list(side = "right"),
q = list(type = "pie", params = list(width = grid::unit(12, "mm"))),
p2 = list(type = "density"),
a = list(type = "simple")
),
show_row_names = TRUE, show_column_names = TRUE
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
Heatmap(data,
values_by = "value", rows_by = "r", columns_by = "c",
split_by = "p", palette = list(x = "Reds", y = "Blues")
)
}
if (requireNamespace("cluster", quietly = TRUE)) {
# implies in_form = "wide-rows"
Heatmap(data, rows_by = c("p1", "p2"), columns_by = "c")
}
if (requireNamespace("cluster", quietly = TRUE)) {
# implies wide-columns
Heatmap(data, rows_by = "r", columns_by = c("p1", "p2"))
}
Atomic heatmap (internal)
Description
Core implementation for drawing a single heatmap using
ComplexHeatmap::Heatmap. This function takes pre-processed data
(already in long format with resolved row/column identifiers) and handles
colour mapping, cell rendering, annotation construction, and the final
draw() call. It is the workhorse behind the exported
Heatmap function and is also reused by
LinkedHeatmapAtomic (via return_ht = TRUE).
Usage
HeatmapAtomic(
data,
values_by,
values_fill = NA,
rows_by = NULL,
rows_split_by = NULL,
columns_by = NULL,
columns_split_by = NULL,
palette = "RdBu",
palcolor = NULL,
palreverse = FALSE,
pie_size_name = "size",
pie_size = NULL,
pie_values = "length",
pie_group_by = NULL,
pie_palette = "Spectral",
pie_palcolor = NULL,
bars_sample = 100,
label = scales::label_number_auto(),
label_size = 10,
label_color = "black",
label_name = "label",
mark = identity,
mark_color = "black",
mark_size = 1,
mark_name = "mark",
violin_fill = NULL,
boxplot_fill = NULL,
dot_size = 8,
dot_size_name = "size",
legend_items = NULL,
legend_discrete = FALSE,
legend.position = "right",
legend.direction = "vertical",
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
add_bg = FALSE,
bg_alpha = 0.5,
keep_na = FALSE,
keep_empty = FALSE,
add_reticle = FALSE,
reticle_color = "grey",
cluster_columns = TRUE,
cluster_rows = TRUE,
show_row_names = NULL,
show_column_names = NULL,
border = TRUE,
title = NULL,
column_title = NULL,
row_title = NULL,
na_col = "grey85",
row_names_side = "right",
column_names_side = "bottom",
row_annotation = NULL,
row_annotation_side = NULL,
row_annotation_palette = NULL,
row_annotation_palcolor = NULL,
row_annotation_type = NULL,
row_annotation_params = NULL,
row_annotation_agg = NULL,
column_annotation = NULL,
column_annotation_side = NULL,
column_annotation_palette = NULL,
column_annotation_palcolor = NULL,
column_annotation_type = NULL,
column_annotation_params = NULL,
column_annotation_agg = NULL,
flip = FALSE,
alpha = 1,
seed = 8525,
padding = 15,
base_size = 1,
aspect.ratio = NULL,
draw_opts = list(),
return_ht = FALSE,
layer_fun_callback = NULL,
cell_type = "tile",
cell_agg = NULL,
...
)
Arguments
data |
A data frame in long format. Each row represents one observation; columns specify row/column membership and the value to encode as colour. |
values_by |
A character of column name in |
values_fill |
A value used to fill missing cells in the matrix.
Default |
rows_by |
A vector of column names in |
rows_split_by |
A character of column name in |
columns_by |
A vector of column names in |
columns_split_by |
A character of column name in |
palette |
A character string naming a palette (see
|
palcolor |
A custom colour vector overriding |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
pie_size_name |
Legend title for the pie size. |
pie_size |
A numeric value or function returning the pie radius. When a function, it receives the count of groups in the pie. |
pie_values |
A function or string (convertible via
|
pie_group_by |
A character of column name in |
pie_palette, pie_palcolor |
Palette and custom colours for pie slice fill colours. |
bars_sample |
Number of observations sampled per cell when
|
label |
A function to compute text labels when
|
label_size |
Default point size for label text (used as fallback
when the |
label_color |
Default colour for label text (fallback). |
label_name |
Legend title for the label colour scale. The legend
is shown automatically when the |
mark |
A function to compute mark symbols when
|
mark_color |
Default mark colour (fallback). |
mark_size |
Default mark stroke width ( |
mark_name |
Legend title for the mark colour scale. |
violin_fill |
A character vector of colours to use as fill for
violin plots when |
boxplot_fill |
A character vector of colours to use as fill for
boxplots when |
dot_size |
Dot size when |
dot_size_name |
Legend title for the dot size. |
legend_items |
A named numeric vector specifying custom legend entries for the main colour scale. Names become the displayed labels. |
legend_discrete |
Logical; if |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
lower_quantile, upper_quantile, lower_cutoff, upper_cutoff |
Quantile or explicit cutoffs for clipping the colour scale. Applied
to aggregated values for |
add_bg |
Logical; if |
bg_alpha |
Numeric in |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
add_reticle |
Logical; if |
reticle_color |
Colour for the reticle lines. |
cluster_columns |
Logical; cluster the columns. If |
cluster_rows |
Logical; cluster the rows. If |
show_row_names |
Logical; show row names. If |
show_column_names |
Logical; show column names. If |
border |
A logical value indicating whether to draw borders around
the heatmap. If |
title |
The global (column) title of the heatmap. |
column_title |
Character string/vector used as the column group annotation title. |
row_title |
Character string/vector used as the row group annotation title. |
na_col |
Colour for |
row_names_side |
Side for row names. Default |
column_names_side |
Side for column names. Default |
row_annotation |
A structured list specifying row annotations.
Same format as |
row_annotation_side |
Deprecated: use
|
row_annotation_palette |
Deprecated: use
|
row_annotation_palcolor |
Deprecated: use
|
row_annotation_type |
Deprecated: use
|
row_annotation_params |
Deprecated: use
|
row_annotation_agg |
Deprecated: use
|
column_annotation |
A structured list specifying column annotations. Each entry is a named list with sub-keys:
Shortcuts:
Special keys:
|
column_annotation_side |
Deprecated: use
|
column_annotation_palette |
Deprecated: use
|
column_annotation_palcolor |
Deprecated: use
|
column_annotation_type |
Deprecated: use
|
column_annotation_params |
Deprecated: use
|
column_annotation_agg |
Deprecated: use
|
flip |
Logical; if |
alpha |
Alpha transparency for heatmap cells in |
seed |
The random seed to use. Default is 8525. |
padding |
Padding around the heatmap in CSS order (top, right,
bottom, left). Supports 1–4 values. Default 15 (mm). Note that
this is different from |
base_size |
A positive numeric scalar used as a scaling factor for the overall heatmap size. Default 1 (no scaling). Values > 1 enlarge all cell dimensions proportionally. |
aspect.ratio |
Height-to-width ratio of a single heatmap cell.
When |
draw_opts |
A named list of additional arguments passed to
|
return_ht |
Logical; if |
layer_fun_callback |
A function to add custom graphical layers on
top of each heatmap cell. Receives |
cell_type |
The type of cell to render. One of |
cell_agg |
A function to aggregate values within each cell when
|
... |
Additional arguments passed to
|
Value
An object of heatmap that is wrapped by patchwork::wrap_plots()
Architecture
-
Annotation resolution — row and column annotation parameters (side, type, palette, params, aggregation) are resolved with alias support (
.row,.col,.rows.split, etc.) so that built-in name/split annotations and user-defined annotations can be configured uniformly. -
Keep-NA / keep-empty handling —
keep_naandkeep_emptyare processed per column to control whetherNAvalues and empty factor levels are preserved in the data before constructing the heatmap matrix. -
Flip — when
flip = TRUE, row and column parameters are swapped transparently so the caller does not need to manually swap every argument. -
Cell dimension calculation — cell width and height are pre-computed from
cell_type,aspect.ratio,base_size, and the unique row/column counts (accounting for split groups). These are passed as explicit"inches"units toComplexHeatmap::Heatmap()so cells have guaranteed physical sizes. -
Colour mapping — the main colour scale is built from
palette/palcolorwith optional quantile-based or explicit cutoff clamping. -
Cell function dispatch — depending on
cell_type, the appropriatecell_funorlayer_funis installed (tile, bars, label, mark, label+mark, dot, violin, boxplot, pie). -
Annotation construction — row and column annotations are built via
ComplexHeatmap::HeatmapAnnotation()using the resolved type and parameters. -
Drawing — the heatmap is drawn via
ComplexHeatmap::draw()with controlled padding and legend collection. Whenreturn_ht = TRUE, the preparedHeatmapobject is returned without drawing. -
Dimension attributes — the returned object carries
height/widthattributes (in inches) andcell_w/cell_hattributes for downstream layout calculations.
Label / mark dispatch contract
The label and mark functions can take 1, 3, or 5
arguments. The first argument is always the aggregated value for a
single cell. With 3 arguments, the second and third are the row and
column indices. With 5 arguments, the fourth and fifth are the row
and column names. The function should return one of:
-
NA— nothing is drawn for this cell. A character scalar — used as the label text / mark type; default size and colour are used.
A named list with fields
label/mark,size,color,legend, andorder(all optional; smallerorderappears first in the legend).
For label cells with custom indices, use
ComplexHeatmap::pindex() to translate between data and heatmap
coordinates.
Supported mark types
-
Primitives:
-(h-line),|(v-line),+(cross),/(l-diag),\(r-diag),x(both diags),o(circle),()(edge-touching circle),<>(diamond). -
With rectangular border:
[],[-],[|],[+],[/],[\],[x],[o],[()],[<>]. -
With full circle:
(-),(|),(+),(/),(\),(x),(o),(<>). -
With diamond:
<->,<|>,<+>,</>,<\>,<x>,<o>. -
Octagon:
{},{-},{|},{+},{/},{\},{x},{o},{()},{<>}. -
Combinations: e.g.
[(|)],[(-)],[(+)],[(/)],[(\],[(x)],[(o)],[(<>)].
Annotations
Row and column annotations are configured via the
row_annotation / column_annotation structured list
arguments. Built-in name annotations (for rows_by /
columns_by) and split annotations (for rows_split_by /
columns_split_by) are added automatically and can be configured
using the aliases .row / .col and .row.split /
.col.split as keys in the annotation list. Setting an alias
entry's params to FALSE disables that annotation.
.default provides default values inherited by all entries
(with recursive merge for params). Ordering within each side:
name annotations are closest to the body, split annotations farthest
away, user-defined annotations in between.
Note
Removed parameters: rows_palette, rows_palcolor,
columns_palette, columns_palcolor,
columns_split_palette, columns_split_palcolor,
rows_split_palette, rows_split_palcolor — use
row_annotation/column_annotation with
sub-key palette/palcolor and alias
.row / .row.split / .col / .col.split.
Also removed:
row_name_annotation, row_name_legend,
column_name_annotation, column_name_legend — set
row_annotation = list(.row = list(params = FALSE)) /
column_annotation = list(.col = list(params = FALSE)).
Jitter plot
Description
Draws a jittered point plot showing the distribution of numeric y-values across a discrete x-axis. Each data point is rendered with random jitter along the x-axis (and optionally the y-axis) to reduce overplotting, making it easy to visualise data density, spread, and outliers within each category.
The function supports x-axis reordering by y-value summaries
(mean or median), group dodging via group_by to compare
subgroups side-by-side, point labelling with automatic top-n
selection using a configurable distance metric (default: radial distance
y^2 + size^2), point highlighting for emphasis, optional
horizontal reference lines, and wide-format input via
in_form. Colour control, faceting, and splitting into separate
sub-plots via split_by are supported.
Usage
JitterPlot(
data,
x,
x_sep = "_",
y = NULL,
in_form = c("long", "wide"),
split_by = NULL,
split_by_sep = "_",
keep_na = FALSE,
keep_empty = FALSE,
sort_x = c("none", "mean_asc", "mean_desc", "mean", "median_asc", "median_desc",
"median"),
flip = FALSE,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
x_text_angle = 0,
order_by = "-({y}^2 + {size_by}^2)",
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = NULL,
legend.position = "right",
legend.direction = "vertical",
shape = 21,
border = "black",
size_by = 2,
size_name = NULL,
size_trans = NULL,
y_nbreaks = 4,
jitter_width = 0.5,
jitter_height = 0,
y_max = NULL,
y_min = NULL,
y_trans = "identity",
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_hline = NULL,
hline_type = "solid",
hline_width = 0.5,
hline_color = "black",
hline_alpha = 1,
labels = NULL,
label_by = NULL,
nlabel = 5,
label_size = 3,
label_fg = "black",
label_bg = "white",
label_bg_r = 0.1,
highlight = NULL,
highlight_color = "red2",
highlight_size = 1,
highlight_alpha = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name for the x-axis.
Must be character or factor. Multiple columns can be provided; they are
concatenated with |
x_sep |
A character string used to join multiple |
y |
A character string specifying the numeric column for the y-axis.
Required when |
in_form |
A character string specifying the input data format. Either
|
split_by |
The column(s) to split the data by and produce separate
sub-plots. Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
sort_x |
A character string controlling x-axis level reordering by
y-value summaries. One of |
flip |
A logical value. When |
group_by |
A character vector of column names for dodging the points.
Each unique combination becomes a separate dodge group and the points are
offset horizontally via |
group_by_sep |
A character string used to join multiple
|
group_name |
A character string for the dodge-group legend title.
When |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
order_by |
A string expression passed to |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value in |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
shape |
A numeric value specifying the point shape (ggplot2 point
shape codes). Shapes 21–25 are filled shapes with borders; for these
shapes the border behaviour is controlled by |
border |
Controls the border of points when the shape has a border
(21–25). If |
size_by |
A numeric column name or a single numeric value controlling
point size. When a column name is provided, sizes are scaled using
|
size_name |
A character string for the size legend title. When
|
size_trans |
A function or a function name (as a string) to transform
the |
y_nbreaks |
A numeric value hinting at the number of break intervals
for the y-axis. Passed to |
jitter_width |
A numeric value controlling the amount of horizontal
jitter (in x-axis units). Passed to |
jitter_height |
A numeric value controlling the amount of vertical
jitter (in y-axis units). Passed to |
y_max, y_min |
Numeric values or quantile strings (e.g. |
y_trans |
A character string specifying a transformation for the
y-axis (e.g. |
add_bg |
A logical value. When |
bg_palette |
A character string specifying the palette for the
background stripe colours. Passed to |
bg_palcolor |
A character vector of colours for the background
stripes. Passed to |
bg_alpha |
A numeric value in |
add_hline |
One or more numeric values specifying y-values at which
to draw horizontal reference lines. When |
hline_type |
A character string specifying the line type for the
horizontal reference line(s). Default: |
hline_width |
A numeric value specifying the line width for the
horizontal reference line(s). Default: |
hline_color |
A character string specifying the colour for the
horizontal reference line(s). Default: |
hline_alpha |
A numeric value in |
labels |
A vector of row names or row indices specifying which points
to label. When |
label_by |
A character string naming a column whose values are used
as label text. When |
nlabel |
An integer specifying the number of points to label per
x-group when |
label_size, label_fg, label_bg, label_bg_r |
Label aesthetics for
|
highlight |
A specification of which points to highlight. Can be:
|
highlight_color |
A character string specifying the colour of
highlighted points. Default: |
highlight_size |
A numeric value specifying the size of highlighted
points. Default: |
highlight_alpha |
A numeric value in |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
A numeric seed for reproducibility. Passed to
|
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default
|
axes |
A character string specifying how axes should be treated
across the combined layout (passed to |
axis_titles |
A character string specifying how axis titles should be
treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should be
collected across panels (passed to |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments. |
Value
A ggplot object (when split_by is NULL), a
patchwork object (when split_by is provided and
combine = TRUE), or a named list of ggplot objects (when
combine = FALSE). All ggplot objects have height
and width attributes in inches.
split_by workflow
When split_by is provided:
-
validate_common_args()validates theseed. -
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments for all relevant columns (x,split_by,group_by,facet_by). The
split_bycolumn is validated viacheck_columns()withforce_factor = TRUE. Multiplesplit_bycolumns are concatenated withsplit_by_sep.If
split_byis notNULL, the data frame is split (preserving factor level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
JitterPlotAtomic()is called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
set.seed(8525)
n <- 180
x <- factor(
sample(c("A", NA, LETTERS[3:5]), n, replace = TRUE),
levels = c("A", "B", "C", "D", "E")
)
group <- factor(
sample(c("G1", NA, "G3"), n, replace = TRUE),
levels = c("G1", "G2", "G3")
)
size <- rexp(n, rate = 1)
id <- paste0("pt", seq_len(n))
y <- rnorm(n, mean = ifelse(is.na(group), 0, ifelse(group == "G1", 0.5, -0.5))) +
as.numeric(ifelse(is.na(x), 0, x))/10
df <- data.frame(
x = x,
y = y,
group = group,
size = size,
id = id
)
# Basic
JitterPlot(df, x = "x", y = "y")
# Keep empty x levels and NA
JitterPlot(df, x = "x", y = "y", keep_na = TRUE, keep_empty = TRUE)
# Map size with transform; legend shows original values
JitterPlot(df, x = "x", y = "y", size_by = "size", size_name = "Abundance",
size_trans = sqrt, order_by = "-y^2")
# Dodge by group and add a horizontal line
JitterPlot(df, x = "x", y = "y", group_by = "group",
add_hline = 0, hline_type = "dashed", hline_color = "red2")
# Keep the empty levels only for color coding
# Note the G3 is not blue (which is taken by unused level G2)
JitterPlot(df, x = "x", y = "y", group_by = "group",
keep_na = TRUE, keep_empty = 'level')
# Label top points by distance (y^2 + size^2)
JitterPlot(df, x = "x", y = "y", size_by = "size", label_by = "id", nlabel = 3)
# Flip axes
JitterPlot(df, x = "x", y = "y", flip = TRUE)
Atomic jitter plot (internal)
Description
Core implementation for drawing a single jittered point plot. This is the
workhorse behind the exported JitterPlot function — it takes a
single data frame (no split_by support) and returns a
ggplot object. The plot displays individual data points with random
jitter along the x-axis (and optionally the y-axis) to reveal the
distribution of values within each x category, making it especially useful
for visualising overlapping discrete data.
The function provides extensive annotation features including point labelling
(via geom_text_repel with automatic top-n selection
using a configurable distance metric), point highlighting, optional dodging
via group_by, and horizontal reference lines. It supports both long
and wide input formats, quantile-based axis limits, and x-axis reordering by
y-value summaries (mean or median).
Usage
JitterPlotAtomic(
data,
x,
x_sep = "_",
y = NULL,
in_form = c("long", "wide"),
keep_na = FALSE,
keep_empty = FALSE,
sort_x = c("none", "mean_asc", "mean_desc", "mean", "median_asc", "median_desc",
"median"),
flip = FALSE,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
x_text_angle = 0,
order_by = "-({y}^2 + {size_by}^2)",
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = NULL,
legend.position = "right",
legend.direction = "vertical",
shape = 21,
border = "black",
size_by = 2,
size_name = NULL,
size_trans = NULL,
y_nbreaks = 4,
jitter_width = 0.5,
jitter_height = 0,
y_max = NULL,
y_min = NULL,
y_trans = "identity",
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_hline = NULL,
hline_type = "solid",
hline_width = 0.5,
hline_color = "black",
hline_alpha = 1,
labels = NULL,
label_by = NULL,
nlabel = 5,
label_size = 3,
label_fg = "black",
label_bg = "white",
label_bg_r = 0.1,
highlight = NULL,
highlight_color = "red2",
highlight_size = 1,
highlight_alpha = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name for the x-axis.
Must be character or factor. Multiple columns can be provided; they are
concatenated with |
x_sep |
A character string used to join multiple |
y |
A character string specifying the numeric column for the y-axis.
Required when |
in_form |
A character string specifying the input data format. Either
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
sort_x |
A character string controlling x-axis level reordering by
y-value summaries. One of |
flip |
A logical value. When |
group_by |
A character vector of column names for dodging the points.
Each unique combination becomes a separate dodge group and the points are
offset horizontally via |
group_by_sep |
A character string used to join multiple
|
group_name |
A character string for the dodge-group legend title.
When |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
order_by |
A string expression passed to |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value in |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
shape |
A numeric value specifying the point shape (ggplot2 point
shape codes). Shapes 21–25 are filled shapes with borders; for these
shapes the border behaviour is controlled by |
border |
Controls the border of points when the shape has a border
(21–25). If |
size_by |
A numeric column name or a single numeric value controlling
point size. When a column name is provided, sizes are scaled using
|
size_name |
A character string for the size legend title. When
|
size_trans |
A function or a function name (as a string) to transform
the |
y_nbreaks |
A numeric value hinting at the number of break intervals
for the y-axis. Passed to |
jitter_width |
A numeric value controlling the amount of horizontal
jitter (in x-axis units). Passed to |
jitter_height |
A numeric value controlling the amount of vertical
jitter (in y-axis units). Passed to |
y_max, y_min |
Numeric values or quantile strings (e.g. |
y_trans |
A character string specifying a transformation for the
y-axis (e.g. |
add_bg |
A logical value. When |
bg_palette |
A character string specifying the palette for the
background stripe colours. Passed to |
bg_palcolor |
A character vector of colours for the background
stripes. Passed to |
bg_alpha |
A numeric value in |
add_hline |
One or more numeric values specifying y-values at which
to draw horizontal reference lines. When |
hline_type |
A character string specifying the line type for the
horizontal reference line(s). Default: |
hline_width |
A numeric value specifying the line width for the
horizontal reference line(s). Default: |
hline_color |
A character string specifying the colour for the
horizontal reference line(s). Default: |
hline_alpha |
A numeric value in |
labels |
A vector of row names or row indices specifying which points
to label. When |
label_by |
A character string naming a column whose values are used
as label text. When |
nlabel |
An integer specifying the number of points to label per
x-group when |
label_size, label_fg, label_bg, label_bg_r |
Label aesthetics for
|
highlight |
A specification of which points to highlight. Can be:
|
highlight_color |
A character string specifying the colour of
highlighted points. Default: |
highlight_size |
A numeric value specifying the size of highlighted
points. Default: |
highlight_alpha |
A numeric value in |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
in_form handling — when
in_form = "wide", the x columns are pivoted to long format viapivot_longer(), creating a key column.xand a value column.y. -
Column resolution —
x,y,group_by, andfacet_byare validated and transformed viacheck_columns. Multi-column inputs forxandgroup_byare concatenated into single columns using their respective separators (x_sep,group_by_sep). -
NA / empty-level handling —
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. Per-columnkeep_emptysettings are extracted forx,group_by, andfacet_byindependently. Whenfacet_byhas more than one column, thekeep_emptyvalues for all facet columns must be identical. -
sort_x resolution —
match.arg()normalises thesort_xargument, and per-group (x,group_by,facet_by) means and medians ofyare computed for subsequent reordering. -
y-axis limit computation —
y_maxandy_minsupport raw numeric values or quantile strings (e.g."q95"), which are resolved viaquantile(). These limits are used for fixedcoord_cartesian/coord_flip. -
Highlight flag — when
highlightis provided, a logical column.highlightis created. Values can beTRUE(all points), a numeric vector of row indices, a single character string parsed as an R expression, or a character vector matched against row names. -
Label preparation — labels are resolved from
label_byor row names. WhenlabelsisNULLandnlabel > 0, the topnlabelpoints per x-group are selected by descending order oforder_by(default:-({y}^2 + {size_by}^2), the radial distance from zero in y-size space, analogous to VolcanoPlot). Whenfacet_byis active, the ranking is nested within each facet panel. -
x-axis reordering — when
sort_xis not"none", the x-axis factor levels are reordered by the per-group mean or median viareorder(). -
Flip handling — when
flip = TRUE, the x-axis factor levels are reversed and the aspect ratio is inverted. -
Colour assignment —
palette_this()assigns colours to the levels ofgroup_by(orxwhengroup_byisNULL), includingNAlevels which are relabelled as"NA". -
Background layer — when
add_bg = TRUE, alternating background stripes are drawn viabg_layer()using the x-axis level order. -
Position jitter — when
group_byisNULL,position_jitter()is used. Whengroup_byis provided,position_jitterdodge()is used so points are dodged by group before jittering. -
Pre-compute jittered positions — a temporary
ggplotis built and rendered viaggplot_build()to extract the actual jittered coordinates. These are stored as.x_jitteredand.y_jitteredcolumns and used by the label layer becausegeom_text_repeldoes not natively respectposition_jitter/position_jitterdodge. -
Point layer —
geom_point()is built with the appropriate aesthetic mapping: fill (for shapes 21–25) or colour (for other shapes) mapped to the grouping variable. Border behaviour for shapes 21–25 is controlled byborder(constant string, mapped to group colour, orNA). Whensize_byis a column, size is mapped viaaes(size). -
Discrete colour/fill scales —
scale_fill_manual()orscale_color_manual()with the assigned palette colours. Whenkeep_emptyisTRUEfor the colour column,drop = FALSEand explicitbreaks/limitspreserve empty levels. An additionalscale_color_manual()is added for border colour whenborder = TRUE. -
Size scale — when
size_byis a column,scale_size_area(max_size = 6)is applied. Ifsize_transis provided, the legend labels show the original (untransformed) values while the mapping uses transformed values. -
Highlight overlay — if any points are highlighted, a second
geom_point()layer is drawn on top using thehighlight_color,highlight_size, andhighlight_alphasettings. The highlight layer does not affect the legend. -
Label layer — if any points are selected for labelling,
geom_text_repel()is rendered at the pre-computed jittered coordinates. -
Horizontal reference lines — when
add_hlineis provided,geom_hline()is drawn using the specified line aesthetics. -
Axes and labels —
scale_x_discrete()(withdrop = !isTRUE(keep_empty_x)),scale_y_continuous(trans = y_trans, n.breaks = y_nbreaks), andlabs()set the axis scale properties and titles. -
Coordinate system — when
flip = TRUE,coord_flip()is used with (or without) fixed y-limits depending on free-scale faceting. Whenflip = FALSE,coord_cartesian()sets the y-axis limits unless free scales are in use. -
Theme —
do_call(theme, theme_args)applies the selected theme, with additionalaspect.ratio, x-axis text rotation, legend position, and legend direction adjustments. Panel grid lines are styled: major y-axis lines (dashed grey) for non-flipped plots; major x-axis lines for flipped plots. -
Dimension calculation —
calculate_plot_dimensions()computes plot height and width from the x-axis category count,aspect.ratio, dodge group count, legend metrics, and label character width. The minimum dimensions account for x-axis label length. The resultingheight/widthattributes are stored on theggplotobject. For flipped plots, the width is set to at leastmax(width, height). -
Faceting —
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided, respecting thekeep_emptysetting for facet variables.
Line plot
Description
Draws a line plot showing the change of a numeric value across the progression of a categorical x-axis variable. Each x-axis category is rendered as a point connected by a line, with support for multiple grouped series, error bars, highlighted points, background stripes, and a horizontal reference line.
Key features:
-
Colour modes: lines and points can be coloured by x category (single-series) or by a
group_byvariable (multi-series), or use a single uniform colour. -
Error bars: additive error bars via
errorbar_sd,errorbar_min, orerrorbar_max. -
Highlighting: specific points can be emphasised with a different colour and size via indices, row names, or a filter expression.
-
Background stripes:
add_bg = TRUEdraws alternating bands for visual grouping. -
Count aggregation: omit
yto plot observation counts per x category.
Usage
LinePlot(
data,
x,
y = NULL,
group_by = NULL,
group_by_sep = "_",
split_by = NULL,
split_by_sep = "_",
fill_point_by_x_if_no_group = TRUE,
color_line_by_x_if_no_group = TRUE,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_errorbars = FALSE,
errorbar_width = 0.1,
errorbar_alpha = 1,
errorbar_color = "grey30",
errorbar_linewidth = 0.75,
errorbar_min = NULL,
errorbar_max = NULL,
errorbar_sd = NULL,
highlight = NULL,
highlight_size = pt_size - 0.75,
highlight_color = "red2",
highlight_alpha = 0.8,
pt_alpha = 1,
pt_size = 5,
keep_na = FALSE,
keep_empty = FALSE,
line_type = "solid",
line_width = 1,
line_alpha = 0.8,
add_hline = FALSE,
hline_type = "solid",
hline_width = 0.5,
hline_color = "black",
hline_alpha = 1,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
facet_by = NULL,
facet_scales = "fixed",
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
facet_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
split_by |
A character vector of column names to split the data by.
Each split level produces a separate sub-plot. Multiple columns are
concatenated with |
split_by_sep |
A character string used to join multiple
|
fill_point_by_x_if_no_group |
A logical value. When TRUE (default),
points are filled by the x-axis categories via the palette when
|
color_line_by_x_if_no_group |
A logical value. When TRUE (default),
lines are coloured by the x-axis categories via the palette when
|
add_bg |
A logical value. When TRUE, alternating background stripes
are drawn via |
bg_palette |
A character string specifying the palette for the
background stripe colours. Default |
bg_palcolor |
A character vector of colours for the background
stripes. When NULL (default), colours are derived from
|
bg_alpha |
A numeric value in |
add_errorbars |
A logical value. When TRUE, error bars are added via
|
errorbar_width |
A numeric value for the width of the error bar caps. Default 0.1. |
errorbar_alpha |
A numeric value in |
errorbar_color |
A character string for the colour of the error
bars. When |
errorbar_linewidth |
A numeric value for the line width of error bars. Default 0.75. |
errorbar_min |
A character string naming the column with the lower
error bar bound. Ignored when |
errorbar_max |
A character string naming the column with the upper
error bar bound. Ignored when |
errorbar_sd |
A character string naming the column with the standard
deviation. When |
highlight |
A vector of row indices, row names, a single string
expression (e.g. |
highlight_size |
A numeric value for the size of highlighted points.
Defaults to |
highlight_color |
A character string for the colour of highlighted
points. Default |
highlight_alpha |
A numeric value in |
pt_alpha |
A numeric value in |
pt_size |
A numeric value for the point size. Default 5. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
line_type |
A character string specifying the line type. Default
|
line_width |
A numeric value for the line width (in mm). Default 1. |
line_alpha |
A numeric value in |
add_hline |
A numeric value specifying the y-intercept of a horizontal reference line. When FALSE (default), no line is drawn. |
hline_type |
A character string specifying the line type of the
horizontal reference line. Default |
hline_width |
A numeric value for the width of the horizontal reference line. Default 0.5. |
hline_color |
A character string for the colour of the horizontal
reference line. Default |
hline_alpha |
A numeric value in |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
combine |
Logical; when TRUE (default), per-split plots are combined
into a single |
nrow, ncol |
Integer number of rows / columns for the combined
layout (passed to |
byrow |
Logical; fill the combined layout by row. Default TRUE
(passed to |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
facet_args |
A list of additional arguments passed to
|
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
A numeric seed for reproducibility. Passed to
|
axes |
A character string specifying how axes should be treated
across the combined layout (passed to
|
axis_titles |
A character string specifying how axis titles should
be treated across the combined layout. Defaults to |
guides |
A character string specifying how guides should be
collected across panels. Passed to |
design |
A custom layout specification for combined plots (passed
to |
... |
Additional arguments. |
Value
A ggplot object, a patchwork object (when
combine = TRUE with split_by), or a named list of
ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by Workflow
When split_by is provided:
-
Column validation –
check_columns()resolvessplit_bywith multi-column concatenation. -
NA / empty pre-processing –
process_keep_na_empty()handleskeep_na/keep_emptyfor the split column before splitting, then removes the split column from the per-split lists. -
Data splitting – splits
databysplit_bylevels, preserving factor level order. Whensplit_by = NULL, the data is wrapped in a single-element list with name"...". -
Per-split palette / colour –
check_palette()andcheck_palcolor()resolve per-split palette and colour overrides. -
Per-split legend –
check_legend()resolveslegend.positionandlegend.directionper split level. -
Per-split title – when
titleis a function, it receives the default title (the split level name) and can return a custom string; otherwisetitle %||% split_levelis used. -
Dispatch – each split subset is passed to
LinePlotAtomic. -
Combination –
combine_plots()assembles the list of plots viapatchwork::wrap_plots, honouringnrow/ncol/byrow/design.
Examples
data <- data.frame(
x = factor(c("A", "B", "C", "D", "A", "B", "C", "D"), levels = LETTERS[1:6]),
y = c(10, 8, 16, 4, 6, 12, 14, 2),
group = c("G1", "G1", "G1", "G1", "G2", "G2", "G2", "G2"),
facet = c("F1", "F1", "F2", "F2", "F3", "F3", "F4", "F4")
)
# --- Basic usage ---
LinePlot(data, x = "x", y = "y")
LinePlot(data, x = "x", y = "y", highlight = "group == 'G1'",
fill_point_by_x_if_no_group = FALSE, color_line_by_x_if_no_group = FALSE)
# --- Grouped lines ---
LinePlot(data, x = "x", y = "y", group_by = "group")
LinePlot(data, x = "x", y = "y", group_by = "group",
add_hline = 10, hline_color = "red")
LinePlot(data, x = "x", y = "y", group_by = "group", add_bg = TRUE,
highlight = "y > 10")
LinePlot(data, x = "x", y = "y", group_by = "group", facet_by = "facet")
LinePlot(data, x = "x", y = "y", group_by = "group", split_by = "facet")
# --- Per-split styling ---
LinePlot(data, x = "x", y = "y", split_by = "group",
palcolor = list(G1 = c("red", "blue"), G2 = c("green", "black")))
# --- keep_na and keep_empty ---
data <- data.frame(
x = factor(c("A", "B", NA, "D", "A", "B", NA, "D"), levels = LETTERS[1:4]),
y = c(10, 8, 16, 4, 6, 12, 14, 2),
group = factor(c("G1", "G1", "G1", NA, NA, "G3", "G3", "G3"),
levels = c("G1", "G2", "G3")),
facet = c("F1", "F1", "F2", "F2", "F3", "F3", "F4", "F4")
)
LinePlot(data, x = "x", y = "y", keep_na = TRUE)
LinePlot(data, x = "x", y = "y", keep_empty = TRUE)
LinePlot(data, x = "x", y = "y", keep_empty = 'level')
LinePlot(data, x = "x", y = "y", group_by = "group", keep_na = TRUE)
LinePlot(data, x = "x", y = "y", group_by = "group", keep_empty = TRUE)
LinePlot(data, x = "x", y = "y", group_by = "group",
keep_empty = list(x = TRUE, group = 'level'))
Atomic line-plot dispatcher (internal)
Description
Dispatcher that routes to LinePlotSingle or
LinePlotGrouped depending on whether group_by is
provided. Handles faceting via facet_plot() after the base
plot is built.
Usage
LinePlotAtomic(
data,
x,
y = NULL,
group_by = NULL,
fill_point_by_x_if_no_group = TRUE,
color_line_by_x_if_no_group = TRUE,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_errorbars = FALSE,
errorbar_width = 0.1,
errorbar_alpha = 1,
errorbar_color = "grey30",
errorbar_linewidth = 0.75,
errorbar_min = NULL,
errorbar_max = NULL,
errorbar_sd = NULL,
highlight = NULL,
highlight_size = pt_size - 0.75,
highlight_color = "red2",
highlight_alpha = 0.8,
pt_alpha = 1,
pt_size = 5,
add_hline = FALSE,
hline_type = "solid",
hline_width = 0.5,
hline_color = "black",
hline_alpha = 1,
line_type = "solid",
line_width = 1,
line_alpha = 0.8,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_empty = FALSE,
keep_na = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_args = list(),
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name for the x-axis. Must be character or factor. |
y |
A character string specifying the numeric column for the y-axis. |
group_by |
A character vector of column names to group the data by.
When NULL, a single-series line plot is drawn via
|
fill_point_by_x_if_no_group |
A logical value. When TRUE (default),
points are filled by the x-axis categories via the palette when
|
color_line_by_x_if_no_group |
A logical value. When TRUE (default),
lines are coloured by the x-axis categories via the palette when
|
add_bg |
A logical value. When TRUE, alternating background stripes
are drawn via |
bg_palette |
A character string specifying the palette for the
background stripe colours. Default |
bg_palcolor |
A character vector of colours for the background
stripes. When NULL (default), colours are derived from
|
bg_alpha |
A numeric value in |
add_errorbars |
A logical value. When TRUE, error bars are added via
|
errorbar_width |
A numeric value for the width of the error bar caps. Default 0.1. |
errorbar_alpha |
A numeric value in |
errorbar_color |
A character string for the colour of the error
bars. When |
errorbar_linewidth |
A numeric value for the line width of error bars. Default 0.75. |
errorbar_min |
A character string naming the column with the lower
error bar bound. Ignored when |
errorbar_max |
A character string naming the column with the upper
error bar bound. Ignored when |
errorbar_sd |
A character string naming the column with the standard
deviation. When |
highlight |
A vector of row indices, row names, a single string
expression (e.g. |
highlight_size |
A numeric value for the size of highlighted points.
Defaults to |
highlight_color |
A character string for the colour of highlighted
points. Default |
highlight_alpha |
A numeric value in |
pt_alpha |
A numeric value in |
pt_size |
A numeric value for the point size. Default 5. |
add_hline |
A numeric value specifying the y-intercept of a horizontal reference line. When FALSE (default), no line is drawn. |
hline_type |
A character string specifying the line type of the
horizontal reference line. Default |
hline_width |
A numeric value for the width of the horizontal reference line. Default 0.5. |
hline_color |
A character string for the colour of the horizontal
reference line. Default |
hline_alpha |
A numeric value in |
line_type |
A character string specifying the line type. Default
|
line_width |
A numeric value for the line width (in mm). Default 1. |
line_alpha |
A numeric value in |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_args |
A list of additional arguments passed to
|
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches).
Dispatch Logic
-
Column resolution –
facet_byis validated viacheck_columns. -
Routing – when
group_by = NULL, delegates toLinePlotSingle(ungrouped, single-series line plot). Whengroup_byis provided, delegates toLinePlotGrouped(multi-series line plot). -
Facet keep_empty consistency – when
facet_bycontains multiple columns, theirkeep_emptyvalues must be identical. -
Faceting –
facet_plot()appliesfacet_wrap/facet_gridwith the resolveddropargument (derived fromkeep_empty).
Multi-series line plot (internal)
Description
Core implementation for drawing a multi-series line plot. This is the
workhorse behind LinePlotAtomic for grouped data – it takes a
single data frame with a group_by column and returns a
ggplot object. Each group receives its own line rendered in a
distinct colour from the palette, with optional error bars, highlighted
points, per-group horizontal reference lines, and background stripes.
Usage
LinePlotGrouped(
data,
x,
y = NULL,
group_by,
group_by_sep = "_",
facet_by = NULL,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_errorbars = FALSE,
errorbar_width = 0.1,
errorbar_alpha = 1,
errorbar_color = "grey30",
errorbar_linewidth = 0.75,
errorbar_min = NULL,
errorbar_max = NULL,
errorbar_sd = NULL,
highlight = NULL,
highlight_size = pt_size - 0.75,
highlight_color = "red2",
highlight_alpha = 0.8,
pt_alpha = 1,
pt_size = 5,
add_hline = FALSE,
hline_type = "solid",
hline_width = 0.5,
hline_color = "black",
hline_alpha = 1,
line_type = "solid",
line_width = 1,
line_alpha = 0.8,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_empty = FALSE,
keep_na = FALSE,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
group_by |
A character vector of column names to group the data by.
Each unique combination becomes a separate line. Multiple columns are
concatenated with |
group_by_sep |
A character string used to join multiple
|
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
add_bg |
A logical value. When TRUE, alternating background stripes
are drawn via |
bg_palette |
A character string specifying the palette for the
background stripe colours. Default |
bg_palcolor |
A character vector of colours for the background
stripes. When NULL (default), colours are derived from
|
bg_alpha |
A numeric value in |
add_errorbars |
A logical value. When TRUE, error bars are added via
|
errorbar_width |
A numeric value for the width of the error bar caps. Default 0.1. |
errorbar_alpha |
A numeric value in |
errorbar_color |
A character string for the colour of the error
bars. When |
errorbar_linewidth |
A numeric value for the line width of error bars. Default 0.75. |
errorbar_min |
A character string naming the column with the lower
error bar bound. Ignored when |
errorbar_max |
A character string naming the column with the upper
error bar bound. Ignored when |
errorbar_sd |
A character string naming the column with the standard
deviation. When |
highlight |
A vector of row indices, row names, a single string
expression (e.g. |
highlight_size |
A numeric value for the size of highlighted points.
Defaults to |
highlight_color |
A character string for the colour of highlighted
points. Default |
highlight_alpha |
A numeric value in |
pt_alpha |
A numeric value in |
pt_size |
A numeric value for the point size. Default 5. |
add_hline |
A numeric value specifying the y-intercept of a horizontal reference line. When FALSE (default), no line is drawn. |
hline_type |
A character string specifying the line type of the
horizontal reference line. Default |
hline_width |
A numeric value for the width of the horizontal reference line. Default 0.5. |
hline_color |
A character string for the colour of the horizontal
reference line. Default |
hline_alpha |
A numeric value in |
line_type |
A character string specifying the line type. Default
|
line_width |
A numeric value for the line width (in mm). Default 1. |
line_alpha |
A numeric value in |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches).
Architecture
-
ggplot dispatch – selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Column resolution –
x(forced to factor),y,group_by(multi-column concatenation supported), andfacet_byare validated viacheck_columns. -
Count aggregation – when
y = NULL, the count of observations per (x,group_by,facet_by) combination is computed and used asy. -
Error bar validation – if
add_errorbars = TRUE, checks that eithererrorbar_min/errorbar_maxorerrorbar_sdis provided. -
NA / empty-level handling –
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. -
Highlight parsing –
highlight(indices, row names, expression string, orTRUE) is resolved to a subset of data rows. -
Background layer – when
add_bg = TRUE, alternating background stripes are drawn viabg_layer(). -
Colour assignment –
palette_this()assigns colours to allgroup_bylevels (includingNA, defaulting to"grey80"). -
Horizontal reference line – when
add_hlineis set, one or moregeom_hline()are added. Ifhline_color = TRUE, each horizontal line is coloured to match the corresponding group colour, andadd_hlinecan be a named vector/ list mapping groups to intercept values. -
Line rendering – lines are coloured and grouped by
group_byviageom_line()withaes(color = group_by, group = group_by)andscale_color_manual(). -
Error bars – when
add_errorbars = TRUE, three colour modes are supported: follow the line colour ("line"), trackgroup_bycolours, or use a constant colour. Error bars are added viageom_errorbar(). -
Point rendering – points are filled per group via
geom_point()withaes(fill = group_by)andscale_fill_manual(). -
Highlight overlay – an additional
geom_point()layer draws highlighted rows in the specified colour and size. -
Plot assembly –
scale_x_discrete(),labs(), theme application, axis styling (angle, grid lines), and legend positioning. -
Dimension calculation –
calculate_plot_dimensions()computesheightandwidthattributes (in inches) from x-axis category count, aspect ratio, and legend metrics (legend entries reflect group levels rather than x levels).
Single-series line plot (internal)
Description
Core implementation for drawing a single-series line plot. This is the
workhorse behind LinePlotAtomic for ungrouped data – it takes a
single data frame (no split_by support) and returns a
ggplot object. Each x-axis category receives its own point and
connecting line, with optional per-x coloring, error bars, highlighted
points, and a horizontal reference line.
Usage
LinePlotSingle(
data,
x,
y = NULL,
fill_point_by_x = TRUE,
color_line_by_x = TRUE,
facet_by = NULL,
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
add_errorbars = FALSE,
errorbar_width = 0.1,
errorbar_alpha = 1,
errorbar_color = "grey30",
errorbar_linewidth = 0.75,
errorbar_min = NULL,
errorbar_max = NULL,
errorbar_sd = NULL,
highlight = NULL,
highlight_size = pt_size - 0.75,
highlight_color = "red2",
highlight_alpha = 0.8,
pt_alpha = 1,
pt_size = 5,
add_hline = FALSE,
hline_type = "solid",
hline_width = 0.5,
hline_color = "black",
hline_alpha = 1,
line_type = "solid",
line_width = 1,
line_alpha = 0.8,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_empty = FALSE,
keep_na = FALSE,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name for the x-axis. Must be character or factor. |
y |
A character string specifying the numeric column for the y-axis.
When |
fill_point_by_x |
A logical value. When TRUE (default), points are filled by the x-axis categories using the palette. When FALSE, all points use the first palette colour. |
color_line_by_x |
A logical value. When TRUE (default), lines are coloured by the x-axis categories using the palette. When FALSE, all lines use the first palette colour. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
add_bg |
A logical value. When TRUE, alternating background stripes
are drawn via |
bg_palette |
A character string specifying the palette for the
background stripe colours. Default |
bg_palcolor |
A character vector of colours for the background
stripes. When NULL (default), colours are derived from
|
bg_alpha |
A numeric value in |
add_errorbars |
A logical value. When TRUE, error bars are added via
|
errorbar_width |
A numeric value for the width of the error bar caps. Default 0.1. |
errorbar_alpha |
A numeric value in |
errorbar_color |
A character string for the colour of the error
bars. When |
errorbar_linewidth |
A numeric value for the line width of error bars. Default 0.75. |
errorbar_min |
A character string naming the column with the lower
error bar bound. Ignored when |
errorbar_max |
A character string naming the column with the upper
error bar bound. Ignored when |
errorbar_sd |
A character string naming the column with the standard
deviation. When |
highlight |
A vector of row indices, row names, a single string
expression (e.g. |
highlight_size |
A numeric value for the size of highlighted points.
Defaults to |
highlight_color |
A character string for the colour of highlighted
points. Default |
highlight_alpha |
A numeric value in |
pt_alpha |
A numeric value in |
pt_size |
A numeric value for the point size. Default 5. |
add_hline |
A numeric value specifying the y-intercept of a horizontal reference line. When FALSE (default), no line is drawn. |
hline_type |
A character string specifying the line type of the
horizontal reference line. Default |
hline_width |
A numeric value for the width of the horizontal reference line. Default 0.5. |
hline_color |
A character string for the colour of the horizontal
reference line. Default |
hline_alpha |
A numeric value in |
line_type |
A character string specifying the line type. Default
|
line_width |
A numeric value for the line width (in mm). Default 1. |
line_alpha |
A numeric value in |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches).
Architecture
-
ggplot dispatch – selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Column resolution –
x(forced to factor),y, andfacet_byare validated viacheck_columns. -
Count aggregation – when
y = NULL, the count of observations per x level (and facet) is computed and used asy. -
Error bar validation – if
add_errorbars = TRUE, checks that eithererrorbar_min/errorbar_maxorerrorbar_sdis provided. -
NA / empty-level handling –
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. -
Highlight parsing –
highlight(indices, row names, expression string, orTRUE) is resolved to a subset of data rows. -
Background layer – when
add_bg = TRUE, alternating background stripes are drawn viabg_layer(). -
Horizontal reference line – when
add_hlineis numeric, ageom_hline()is added at that intercept. -
Colour assignment –
palette_this()assigns colours to all x-axis levels (includingNA, defaulting to"grey80"). -
Line rendering – when
color_line_by_x = TRUE, lines are coloured per x level viageom_line()withaes(color = x)andscale_color_manual(). Otherwise a single colour (the first palette entry) is used. -
Error bars – when
add_errorbars = TRUE, three colour modes are supported: follow the line colour ("line"), track x levels, or use a constant colour. Error bars are added viageom_errorbar(). -
Point rendering – when
fill_point_by_x = TRUE, points are filled per x level viageom_point()withaes(fill = x)andscale_fill_manual(). Otherwise a single fill colour (first palette entry) is used. -
Highlight overlay – an additional
geom_point()layer draws highlighted rows in the specified colour and size. -
Plot assembly –
scale_x_discrete(),labs(), theme application, axis styling (angle, grid lines), and legend positioning. -
Dimension calculation –
calculate_plot_dimensions()computesheightandwidthattributes (in inches) from x-axis category count, aspect ratio, and legend metrics.
Linked Heatmap
Description
Draw two heatmaps side-by-side with spline link lines connecting matching rows across the two heatmaps. This is the public, exported interface for creating linked-heatmap visualisations.
A typical use case is visualising ligand–receptor interactions: the left heatmap shows ligand expression (rows = ligands, columns = cell sources), the right heatmap shows receptor expression (rows = receptors, columns = cell targets), and link curves connect each ligand to its cognate receptor(s).
Usage
LinkedHeatmap(
data,
values_by,
values_fill = NA,
name = NULL,
split_by = NULL,
split_by_sep = "_",
rows_by = NULL,
rows_by_sep = "_",
rows_split_by = NULL,
rows_split_by_sep = "_",
columns_by = NULL,
columns_by_sep = "_",
columns_split_by = NULL,
columns_split_by_sep = "_",
rows_data = NULL,
columns_data = NULL,
keep_na = FALSE,
keep_empty = FALSE,
rows_orderby = NULL,
columns_orderby = NULL,
columns_name = NULL,
columns_split_name = NULL,
rows_name = NULL,
rows_split_name = NULL,
palette = "RdBu",
palcolor = NULL,
palreverse = FALSE,
pie_size_name = "size",
pie_size = NULL,
pie_values = "length",
pie_name = NULL,
pie_group_by = NULL,
pie_group_by_sep = "_",
pie_palette = "Spectral",
pie_palcolor = NULL,
bars_sample = 100,
label = identity,
label_size = 10,
label_color = "black",
label_name = "label",
mark = identity,
mark_color = "black",
mark_size = 1,
mark_name = "mark",
violin_fill = NULL,
boxplot_fill = NULL,
dot_size = 8,
dot_size_name = "size",
legend_items = NULL,
legend_discrete = FALSE,
legend.position = "right",
legend.direction = "vertical",
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
add_bg = FALSE,
bg_alpha = 0.5,
add_reticle = FALSE,
reticle_color = "grey",
cluster_columns = NULL,
cluster_rows = NULL,
show_row_names = NULL,
show_column_names = NULL,
border = TRUE,
title = NULL,
title_params = NULL,
column_title = NULL,
row_title = NULL,
na_col = "grey85",
row_names_side = "right",
column_names_side = "bottom",
row_annotation = NULL,
row_annotation_side = NULL,
row_annotation_palette = NULL,
row_annotation_palcolor = NULL,
row_annotation_type = NULL,
row_annotation_params = NULL,
row_annotation_agg = NULL,
column_annotation = NULL,
column_annotation_side = NULL,
column_annotation_palette = NULL,
column_annotation_palcolor = NULL,
column_annotation_type = NULL,
column_annotation_params = NULL,
column_annotation_agg = NULL,
link_width_by = NULL,
link_width_scale = 5,
link_color = "grey40",
link_alpha = 0.6,
flip = FALSE,
alpha = 1,
seed = 8525,
padding = 15,
base_size = 1,
aspect.ratio = NULL,
draw_opts = list(),
layer_fun_callback = NULL,
cell_type = c("tile", "bars", "label", "mark", "label+mark", "mark+label", "dot",
"violin", "boxplot", "pie"),
cell_agg = NULL,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame in long format. Each row represents one observation; columns specify row/column membership for both left and right heatmaps as well as the values to encode as color. |
values_by |
Default column name for heatmap cell values. Used as
fallback when |
values_fill |
A value used to fill missing cells in the matrix
(passed to |
name |
Default legend title for the colour scale. Used as fallback
when |
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
rows_by |
Default column for rows in both heatmaps. Used as
fallback for |
rows_by_sep |
Separator for concatenated |
rows_split_by |
Optional column name to split the rows of both
heatmaps into groups (passed as |
rows_split_by_sep |
Separator for concatenated
|
columns_by |
Default column for columns in both heatmaps. Used as
fallback for |
columns_by_sep |
Separator for concatenated |
columns_split_by |
Default column to split columns into groups.
Used as fallback for |
columns_split_by_sep |
Separator for concatenated
|
rows_data, columns_data |
Optional data frames providing additional
row / column metadata for annotations. Passed through to
|
keep_na, keep_empty |
Passed through to |
rows_orderby, columns_orderby |
Column name to order rows / columns by (disables clustering when set). |
columns_name |
Display name for the column annotation. |
columns_split_name |
Display name for the column split annotation. |
rows_name |
Display name for the row annotation. |
rows_split_name |
Display name for the row split annotation. |
palette |
A character string naming a palette (see
|
palcolor |
A custom colour vector that overrides |
palreverse |
Logical; if |
pie_size_name |
Legend title for the pie size when
|
pie_size |
A numeric value or function returning the pie radius. When a function, it receives the count of groups in the pie and should return a radius. |
pie_values |
A function or string (convertible via
|
pie_name |
Default name for the pie legend. Used as fallback for
|
pie_group_by |
Default column(s) for pie grouping. Used as fallback
for |
pie_group_by_sep |
Separator for concatenated |
pie_palette, pie_palcolor |
Palette and custom colours for pie slice fill colours. |
bars_sample |
Number of observations sampled per cell when
|
label |
A function to compute text labels when
|
label_size |
Default point size for label text (used as fallback
when the |
label_color |
Default colour for label text (used as fallback when
the |
label_name |
Legend title for the label colour scale. |
mark |
A function to compute mark symbols when
|
mark_color |
Default mark colour (fallback). |
mark_size |
Default mark stroke width in pt (fallback). |
mark_name |
Legend title for the mark colour scale. |
violin_fill |
A character vector of colours to use as fill for
violin plots when |
boxplot_fill |
A character vector of colours to use as fill for
boxplots when |
dot_size |
Dot size when |
dot_size_name |
Legend title for the dot size. |
legend_items |
A named numeric vector specifying custom legend entries for the main colour scale. Names become the displayed labels. |
legend_discrete |
Logical; if |
legend.position |
A character string specifying where to place the
combined legend: |
legend.direction |
Legend stacking direction:
|
lower_quantile, upper_quantile |
Quantiles used for clipping the
colour scale when |
lower_cutoff, upper_cutoff |
Explicit cutoffs for the colour scale.
Values outside the range are clamped (winsorized). Override
|
add_bg |
Logical; if |
bg_alpha |
Numeric in |
add_reticle |
Logical; if |
reticle_color |
Colour for the reticle lines. |
cluster_columns |
Logical; cluster columns in both heatmaps.
|
cluster_rows |
Default clustering setting for rows. Used as
fallback for |
show_row_names, show_column_names |
Logical; show row/column names. |
border |
Logical; draw a border around each heatmap. Default
|
title |
A character string for the overall plot title. A function
can be used to generate a dynamic title from the default.
Note that, |
title_params |
A list of parameters passed to |
column_title, row_title |
Character title displayed above the columns / beside the rows of each heatmap. |
na_col |
Colour used for |
row_names_side |
Default side for row names. Used as fallback for
|
column_names_side |
Side for column names. Default
|
row_annotation |
A structured list specifying row annotations.
See |
row_annotation_side |
Deprecated: use
|
row_annotation_palette |
Deprecated: use
|
row_annotation_palcolor |
Deprecated: use
|
row_annotation_type |
Deprecated: use
|
row_annotation_params |
Deprecated: use
|
row_annotation_agg |
Deprecated: use
|
column_annotation |
A structured list specifying column annotations.
See |
column_annotation_side |
Deprecated: use
|
column_annotation_palette |
Deprecated: use
|
column_annotation_palcolor |
Deprecated: use
|
column_annotation_type |
Deprecated: use
|
column_annotation_params |
Deprecated: use
|
column_annotation_agg |
Deprecated: use
|
link_width_by |
Optional column name in |
link_width_scale |
Numeric scaling factor applied to the normalised
link intensity values to produce final line widths ( |
link_color |
Colour of the link spline curves. Default
|
link_alpha |
Alpha transparency of link curves in |
flip |
Logical; must be |
alpha |
Alpha transparency for heatmap cells in |
seed |
Random seed for reproducibility. Default 8525. |
padding |
Padding around the heatmap in CSS order (top, right, bottom, left). Supports 1–4 values. Default 15 (mm). |
base_size |
A positive numeric scalar used as a scaling factor for the overall heatmap size. Default 1 (no scaling). Values > 1 enlarge all cell dimensions proportionally. |
aspect.ratio |
Height-to-width ratio of a single heatmap cell.
When |
draw_opts |
A named list of additional arguments passed to
|
layer_fun_callback |
A function to add custom graphical layers on
top of each heatmap cell. Receives |
cell_type |
The type of cell to render. One of |
cell_agg |
A function to aggregate values within each cell when
|
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments passed to |
Value
A patchwork object (class wrap_plots) with
height and width attributes (in inches). When
combine = FALSE, a named list of such objects, one per
split_by level.
Left / right specification
Parameters that differ between the two heatmaps are prefixed with
left_ or right_. Shared parameters (e.g. palette,
cell_type, cluster_columns) apply to both sides but can be
overridden per-side via the ... argument. Every parameter listed
below can also be passed with a left_ or right_ prefix in
... for full per-side control.
The ... argument is also forwarded to
Heatmap after prefix-stripping, allowing
direct access to ComplexHeatmap parameters (e.g.
left_row_names_gp, right_column_names_rot).
Split-by support
When split_by is provided, the data is partitioned into subsets
and an independent linked-heatmap pair is produced for each level. The
results are combined via wrap_plots according to
nrow, ncol, byrow, and design.
Per-split palette, palcolor, and legend.position can
be specified as named lists keyed by split level.
Dimension calculation
Cell dimensions are pre-computed from cell_type,
aspect.ratio, base_size, and the unique row/column counts
in the data (accounting for split groups). These exact dimensions are
passed to ComplexHeatmap::Heatmap so cells have guaranteed
physical sizes, ensuring that the two heatmaps' bodies align precisely
and that link line endpoints land on the correct rows. The final
height / width attributes on the returned object include
legend space and are clamped to [4, 64] inches with aspect-ratio
correction.
See Also
Examples
set.seed(8525)
# Define sparse ligand-receptor pairs
pairs_df <- data.frame(
ligand = c("Ligand1", "Ligand2", "Ligand3", "Ligand4", "Ligand5",
"Ligand1", "Ligand3", "Ligand5"),
receptor = c("Receptor1", "Receptor2", "Receptor1", "Receptor3", "Receptor4",
"Receptor5", "Receptor2", "Receptor5"),
stringsAsFactors = FALSE
)
sources <- paste0("Source", 1:4)
targets <- paste0("Target", 1:6)
# Expand pairs across all sources and targets
data <- merge(
merge(pairs_df, data.frame(source = sources, stringsAsFactors = FALSE)),
data.frame(target = targets, stringsAsFactors = FALSE)
)
data$split <- sample(c("A", "B"), nrow(data), replace = TRUE)
data$ligand_expr <- runif(nrow(data), 0, 10)
data$receptor_expr <- runif(nrow(data), 0, 10)
data$intensity <- runif(nrow(data), 0, 1)
if (requireNamespace("ComplexHeatmap", quietly = TRUE)) {
LinkedHeatmap(
data,
show_column_names = TRUE,
column_names_side = "bottom",
show_row_names = FALSE,
left_row_names_side = "right",
left_rows_by = "ligand",
left_columns_by = "source",
left_values_by = "ligand_expr",
left_name = "Ligand",
left_row_annotation = list(
.row = list(
type = "label",
params = list(labels_rot = 0),
side = "right"
)
),
right_cluster_rows = FALSE,
right_row_names_side = "left",
right_row_annotation = list(
.row = list(
type = "label",
params = list(labels_rot = 0),
side = "left"
)
),
right_rows_by = "receptor",
right_columns_by = "target",
right_values_by = "receptor_expr",
right_name = "Receptor",
link_width_by = "intensity"
)
}
Atomic linked heatmap (internal)
Description
Draws two heatmaps side-by-side with spline link lines connecting matching
rows across the left and right heatmaps. This is the core implementation
layer — it takes a single data frame and a full set of left/right
parameters, delegates to HeatmapAtomic (with
return_ht = TRUE) to obtain prepared ComplexHeatmap::Heatmap
objects, extracts exact dimension information, and then assembles
everything into a composite grid layout.
Usage
LinkedHeatmapAtomic(
data,
left_values_by,
right_values_by,
left_rows_by,
right_rows_by,
left_columns_by,
right_columns_by,
left_columns_split_by = NULL,
right_columns_split_by = NULL,
left_pie_group_by = NULL,
right_pie_group_by = NULL,
rows_split_by = NULL,
values_fill = NA,
palette = "RdBu",
palcolor = NULL,
palreverse = FALSE,
pie_size_name = "size",
pie_size = NULL,
pie_values = "length",
pie_palette = "Spectral",
pie_palcolor = NULL,
bars_sample = 100,
label = identity,
label_size = 10,
label_color = "black",
label_name = "label",
mark = identity,
mark_color = "black",
mark_size = 1,
mark_name = "mark",
violin_fill = NULL,
boxplot_fill = NULL,
dot_size = 8,
dot_size_name = "size",
legend_items = NULL,
legend_discrete = FALSE,
legend.position = "right",
legend.direction = "vertical",
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
add_bg = FALSE,
bg_alpha = 0.5,
keep_na = FALSE,
keep_empty = FALSE,
add_reticle = FALSE,
reticle_color = "grey",
left_cluster_rows = NULL,
right_cluster_rows = NULL,
cluster_columns = NULL,
show_row_names = NULL,
show_column_names = NULL,
border = TRUE,
title = NULL,
title_params = NULL,
column_title = NULL,
row_title = NULL,
na_col = "grey85",
column_names_side = "bottom",
row_annotation = NULL,
row_annotation_side = NULL,
row_annotation_palette = NULL,
row_annotation_palcolor = NULL,
row_annotation_type = NULL,
row_annotation_params = NULL,
row_annotation_agg = NULL,
column_annotation = NULL,
column_annotation_side = NULL,
column_annotation_palette = NULL,
column_annotation_palcolor = NULL,
column_annotation_type = NULL,
column_annotation_params = NULL,
column_annotation_agg = NULL,
links_span = 0.5,
link_width_by = NULL,
link_width_scale = 5,
link_color = "grey30",
link_alpha = 0.8,
alpha = 1,
seed = 8525,
padding = 15,
base_size = 1,
aspect.ratio = NULL,
draw_opts = list(),
layer_fun_callback = NULL,
cell_type = c("tile", "bars", "label", "mark", "label+mark", "mark+label", "dot",
"violin", "boxplot", "pie"),
cell_agg = NULL,
...
)
Arguments
data |
A data frame in long format. Each row represents one observation; columns specify row/column membership for both left and right heatmaps as well as the values to encode as color. |
left_values_by, right_values_by |
Column name whose values determine the fill color of cells in the left / right heatmap. These are the primary data columns visualized by the colour scale. |
left_rows_by, right_rows_by |
Column name that defines the rows of the left / right heatmap. Each unique value becomes one row. |
left_columns_by, right_columns_by |
Column name that defines the columns of the left / right heatmap. Each unique value becomes one column. |
left_columns_split_by, right_columns_split_by |
Optional column name
to split the columns of the left / right heatmap into groups (passed to
|
left_pie_group_by, right_pie_group_by |
When |
rows_split_by |
Optional column name to split the rows of both
heatmaps into groups (passed as |
values_fill |
A value used to fill missing cells in the matrix
(passed to |
palette |
A character string naming a palette (see
|
palcolor |
A custom colour vector that overrides |
palreverse |
Logical; if |
pie_size_name |
Legend title for the pie size when
|
pie_size |
A numeric value or function returning the pie radius. When a function, it receives the count of groups in the pie and should return a radius. |
pie_values |
A function or string (convertible via
|
pie_palette, pie_palcolor |
Palette and custom colours for pie slice fill colours. |
bars_sample |
Number of observations sampled per cell when
|
label |
A function to compute text labels when
|
label_size |
Default point size for label text (used as fallback
when the |
label_color |
Default colour for label text (used as fallback when
the |
label_name |
Legend title for the label colour scale. |
mark |
A function to compute mark symbols when
|
mark_color |
Default mark colour (fallback). |
mark_size |
Default mark stroke width in pt (fallback). |
mark_name |
Legend title for the mark colour scale. |
violin_fill |
A character vector of colours to use as fill for
violin plots when |
boxplot_fill |
A character vector of colours to use as fill for
boxplots when |
dot_size |
Dot size when |
dot_size_name |
Legend title for the dot size. |
legend_items |
A named numeric vector specifying custom legend entries for the main colour scale. Names become the displayed labels. |
legend_discrete |
Logical; if |
legend.position |
A character string specifying where to place the
combined legend: |
legend.direction |
Legend stacking direction:
|
lower_quantile, upper_quantile |
Quantiles used for clipping the
colour scale when |
lower_cutoff, upper_cutoff |
Explicit cutoffs for the colour scale.
Values outside the range are clamped (winsorized). Override
|
add_bg |
Logical; if |
bg_alpha |
Numeric in |
keep_na, keep_empty |
Passed through to |
add_reticle |
Logical; if |
reticle_color |
Colour for the reticle lines. |
left_cluster_rows, right_cluster_rows |
Logical controlling whether
rows are clustered in the left / right heatmap. |
cluster_columns |
Logical; cluster columns in both heatmaps.
|
show_row_names, show_column_names |
Logical; show row/column names. |
border |
Logical; draw a border around each heatmap. Default
|
title |
A character string for the overall plot title. A function
can be used to generate a dynamic title from the default.
Note that, |
title_params |
A list of parameters passed to |
column_title, row_title |
Character title displayed above the columns / beside the rows of each heatmap. |
na_col |
Colour used for |
column_names_side |
Side for column names. Default
|
row_annotation |
A structured list specifying row annotations.
See |
row_annotation_side |
Deprecated: use
|
row_annotation_palette |
Deprecated: use
|
row_annotation_palcolor |
Deprecated: use
|
row_annotation_type |
Deprecated: use
|
row_annotation_params |
Deprecated: use
|
row_annotation_agg |
Deprecated: use
|
column_annotation |
A structured list specifying column annotations.
See |
column_annotation_side |
Deprecated: use
|
column_annotation_palette |
Deprecated: use
|
column_annotation_palcolor |
Deprecated: use
|
column_annotation_type |
Deprecated: use
|
column_annotation_params |
Deprecated: use
|
column_annotation_agg |
Deprecated: use
|
links_span |
Width (in inches) of the gap column between the two heatmaps where link curves are drawn. Default 0.5. |
link_width_by |
Optional column name in |
link_width_scale |
Numeric scaling factor applied to the normalised
link intensity values to produce final line widths ( |
link_color |
Colour of the link spline curves. Default
|
link_alpha |
Alpha transparency of link curves in |
alpha |
Alpha transparency for heatmap cells in |
seed |
Random seed for reproducibility. Default 8525. |
padding |
Padding around the heatmap in CSS order (top, right, bottom, left). Supports 1–4 values. Default 15 (mm). |
base_size |
A positive numeric scalar used as a scaling factor for the overall heatmap size. Default 1 (no scaling). Values > 1 enlarge all cell dimensions proportionally. |
aspect.ratio |
Height-to-width ratio of a single heatmap cell.
When |
draw_opts |
A named list of additional arguments passed to
|
layer_fun_callback |
A function to add custom graphical layers on
top of each heatmap cell. Receives |
cell_type |
The type of cell to render. One of |
cell_agg |
A function to aggregate values within each cell when
|
... |
Additional arguments passed to
|
Value
A patchwork-wrapped grob (class wrap_plots) with
height and width attributes (in inches). The original
data is stored in p$data.
Architecture
-
Parameter resolution — extra arguments passed via
...are split into left-specific and right-specific groups by prefix (left_vsright_). Each group is merged with the shared defaults using%||%fallback chains, giving the caller full per-side override capability. -
Cell dimension pre-computation — the internal helper
.get_dim_pre()calculates exact cell width and height (in"inches"units) fromcell_type,aspect.ratio,base_size, and the unique row/column counts (including split groups). These are passed as explicitwidth/heightarguments toComplexHeatmap::Heatmap()so that cells have a guaranteed physical size rather than usingnullunits. -
Delegation to
HeatmapAtomic— both the left and right heatmaps are created by callingdo_call(HeatmapAtomic, ...)withreturn_ht = TRUE. This returns the preparedHeatmapobject (withcell_w/cell_hattributes) without drawing it. -
Dimension extraction — exact component heights and widths are read from the prepared
Heatmapobjects viaComplexHeatmap:::component_height()andComplexHeatmap:::component_width(). These 9-element vectors break down every part of the heatmap (title, dendrogram, names, annotations, body) so the composite layout can be sized precisely. -
Link table construction — rows in the left and right heatmaps are matched by grouping the input data on the row identifier columns (plus optional
rows_split_by). Each link's position is mapped to the ordered row index in its respective heatmap (respecting clustering order). -
Legend collection — legends from both heatmaps are collected, packed via
ComplexHeatmap::packLegend(), and placed according tolegend.position(left, right, top, or bottom). -
Composite drawing — a
grid.layoutis built dynamically based on the legend position. Each heatmap is drawn inside a centered, exact-size viewport soComplexHeatmap::draw()sizes the body to the pre-computed row/column counts. Link lines are drawn asgrid.xspline()curves in a dedicated gap column between the two heatmaps. -
Dimension attributes — the final
patchwork-wrapped grob carriesheightandwidthattributes (in inches) for consistent rendering in downstream layouts.
Manhattan plot
Description
Renders a publication-quality Manhattan plot for genetic association
results. The y-axis displays -\log_{10}(p) (or a user-specified
transformation) of p-values, and the x-axis shows genomic positions
organised by chromosome. Each chromosome is rendered in alternating
colours, and configurable horizontal dashed lines mark genome-wide
significance thresholds.
The function is adapted from ggmanh::manhattan_plot() with
extended control over point appearance, variant labels, highlighting,
data thinning, y-axis rescaling, and split_by support for
creating multi-panel layouts (e.g. faceted by cohort or phenotype).
Usage
ManhattanPlot(
data,
chr_by,
pos_by,
pval_by,
split_by = NULL,
split_by_sep = "_",
label_by = NULL,
chromosomes = NULL,
pt_size = 0.75,
pt_color = NULL,
pt_alpha = alpha,
pt_shape = 19,
label_size = 3,
label_fg = NULL,
highlight = NULL,
highlight_color = NULL,
highlight_size = 1.5,
highlight_alpha = 1,
highlight_shape = 19,
preserve_position = TRUE,
chr_gap_scaling = 1,
pval_transform = "-log10",
signif = c(5e-08, 1e-05),
signif_color = NULL,
signif_rel_pos = 0.2,
signif_label = TRUE,
signif_label_size = 3.5,
signif_label_pos = c("left", "right"),
thin = NULL,
thin_n = 1000,
thin_bins = 200,
rescale = TRUE,
rescale_ratio_threshold = 5,
palette = "Dark2",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = expression("-" * log[10](p)),
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
facet_by = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
chr_by |
A character string specifying the column name for chromosome
identifiers. Default: |
pos_by |
A character string specifying the column name for genomic
positions (integer or numeric). Default: |
pval_by |
A character string specifying the column name for p-values
(numeric). Default: |
split_by |
The column(s) to split data by and produce separate
sub-plots. Multiple columns are concatenated with
|
split_by_sep |
A character string used to concatenate multiple
|
label_by |
A character string specifying the column name for variant
labels. Only variants with non-empty values in this column will be
labelled. Default: |
chromosomes |
A character or numeric vector specifying which
chromosomes to include and/or their display order. When |
pt_size |
A numeric value specifying the size of the points.
Default: |
pt_color |
A character string specifying a single colour for all
background (non-highlighted) points. When |
pt_alpha |
A numeric value in |
pt_shape |
A numeric value specifying the shape of the points.
Default: |
label_size |
A numeric value specifying the font size of the
variant labels. Default: |
label_fg |
A character string specifying the colour of the variant
labels. When |
highlight |
Either a numeric vector of row indices or a character
string containing an R expression (parsed via
|
highlight_color |
A character string specifying the colour of
highlighted points. When |
highlight_size |
A numeric value specifying the size of
highlighted points. Default: |
highlight_alpha |
A numeric value in |
highlight_shape |
A numeric value specifying the shape of
highlighted points. Default: |
preserve_position |
A logical value. When |
chr_gap_scaling |
A numeric scaling factor for the gap between
chromosomes. Larger values increase the gap. Default: |
pval_transform |
A function or character string that can be
evaluated to a function for transforming p-values. Default:
|
signif |
A numeric vector of significance thresholds to draw as
horizontal dashed lines. Default: |
signif_color |
A character vector of colours for the significance
threshold lines, of equal length as |
signif_rel_pos |
A numeric value between |
signif_label |
A logical value. When |
signif_label_size |
A numeric value for the font size of the
significance threshold labels. Default: |
signif_label_pos |
A character string specifying where to place
the significance threshold labels: |
thin |
A logical value indicating whether to thin dense data by
sampling points per horizontal partition. Defaults to |
thin_n |
An integer specifying the maximum number of points per
horizontal partition after thinning. Default: |
thin_bins |
An integer specifying the number of horizontal bins
for thinning. Default: |
rescale |
A logical value. When |
rescale_ratio_threshold |
A numeric threshold for triggering
y-axis rescaling. The ratio is computed as
|
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
A numeric seed for reproducibility. Passed to
|
combine |
A logical value. When |
nrow, ncol, byrow |
Integers controlling the layout of combined
plots via |
axes, axis_titles |
Strings controlling how axes and axis titles
are handled across combined plots. Passed to
|
guides |
A string controlling guide collection across combined
plots. Passed to |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
design |
A custom layout specification for combined plots.
Passed to |
... |
Additional arguments. |
Value
A ggplot object (single plot, no split_by), a
patchwork object (when combine = TRUE with
split_by), or a named list of ggplot objects (when
combine = FALSE). Each individual plot carries
height and width attributes.
split_by Workflow
When split_by is provided:
-
Column validation —
check_columns()resolvessplit_bywithforce_factor = TRUE,allow_multi = TRUE, andconcat_multi = TRUE. ForGRangesinputs, validation is performed on the@elementMetadataslot. -
GRanges support —
datacan be adata.frameor aGenomicRanges::GRangesobject. WhenGRangesis used,split_byis read from the metadata columns. -
Data splitting — drops unused
split_bylevels, splitsdatabysplit_by(preserving factor level order), and wraps into a named list. Whensplit_byisNULL, the data is wrapped as a single-element list with name"...". -
Per-split palette / colour —
check_palette()andcheck_palcolor()resolve per-split palette and colour overrides. -
Per-split title — when
titleis a function, it receives the default title (the split level name) and can return a custom string; otherwisetitle %||% split_levelis used. -
Dispatch — each split subset is passed to
ManhattanPlotAtomic. -
Combination —
combine_plots()assembles the list of plots viapatchwork::wrap_plots, honouringnrow/ncol/byrow/design.
Note
facet_by is not supported by this plot type and triggers
a warning if provided. Use split_by instead to produce
comparable multi-panel layouts.
Examples
set.seed(1000)
nsim <- 50000
# --- Data simulation ---
simdata <- data.frame(
"chromosome" = sample(c(1:22,"X"), size = nsim, replace = TRUE),
"position" = sample(1:100000000, size = nsim),
"P.value" = rbeta(nsim, shape1 = 5, shape2 = 1)^7,
"cohort" = sample(c("A", "B"), size = nsim, replace = TRUE)
)
simdata$chromosome <- factor(simdata$chromosome, c(1:22, "X"))
options(repr.plot.width=10, repr.plot.height=5)
# --- Basic Manhattan plot ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
title = "Simulated P.Values", ylab = "P")
}
# --- split_by ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
title = "Simulated P.Values", ylab = "P", split_by = "cohort", ncol = 1)
}
# --- Customized p-value transformation and significance threshold line colors ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
title = "Simulated -Log2 P.Values", ylab = "-log2(P)", pval_transform = "-log2",
signif_color = c("red", "blue"))
}
# --- Different palette and no significance threshold labels ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
palette = "Set1", signif_label = FALSE)
}
# --- Reverse palette and label position on the right ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
palette = "Set1", palreverse = TRUE, signif_label_pos = "right")
}
# --- Single chromosome ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
title = "Simulated P.Values", chromosomes = 5)
}
# --- Chromosome subset and reorder ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
title = "Simulated P.Values", chromosomes = c(20, 4, 6))
}
tmpdata <- data.frame(
"chromosome" = c(rep(5, 10), rep(21, 5)),
"position" = c(sample(250000:250100, 10, replace = FALSE),
sample(590000:600000, 5, replace = FALSE)),
"P.value" = c(10^-(rnorm(10, 100, 3)), 10^-rnorm(5, 9, 1)),
"cohort" = c(rep("A", 10), rep("B", 5))
)
simdata <- rbind(simdata, tmpdata)
simdata$chromosome <- factor(simdata$chromosome, c(1:22, "X"))
# --- Disable y-axis rescaling ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
title = "Simulated P.Values - Significant", rescale = FALSE)
}
# --- Y-axis rescaling with custom break position ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(
simdata, pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
title = "Simulated P.Values - Significant", rescale = TRUE, signif_rel_pos = 0.5)
}
sig <- simdata$P.value < 5e-07
simdata$label <- ""
simdata$label[sig] <- sprintf("Label: %i", 1:sum(sig))
simdata$label2 <- ""
i <- (simdata$chromosome == 5) & (simdata$P.value < 5e-8)
simdata$label2[i] <- paste("Chromosome 5 label", 1:sum(i))
# --- Variant labels ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(simdata, label_by = "label", pval_by = "P.value", chr_by = "chromosome",
pos_by = "position", title = "Simulated P.Values with labels", label_size = 4)
}
# --- Variant labels with custom color ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(simdata, label_by = "label2", pval_by = "P.value", chr_by = "chromosome",
pos_by = "position", title = "Simulated P.Values with labels",
label_size = 3, label_fg = "black")
}
simdata$color <- "Not Significant"
simdata$color[simdata$P.value <= 5e-8] <- "Significant"
# --- Highlight points with custom shape ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(simdata, title = "Highlight Points with shapes",
pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
highlight = "color == 'Significant'", highlight_color = NULL, highlight_shape = 6,
highlight_size = 5, pt_alpha = 0.2, pt_size = 1)
}
# --- Highlight points with custom color ---
if (requireNamespace("ggmanh", quietly = TRUE)) {
ManhattanPlot(simdata, title = "Highlight Points",
pval_by = "P.value", chr_by = "chromosome", pos_by = "position",
highlight = "color == 'Significant'", highlight_color = "black",
pt_color = "lightblue", pt_alpha = 0.2, pt_size = 0.1)
}
Atomic Manhattan plot (internal)
Description
Core implementation for drawing a GWAS-style Manhattan plot. This is the
internal workhorse dispatched by the exported ManhattanPlot
function — it takes a single data frame (no split_by support)
and returns a ggplot object. The plot displays genetic association
p-values across chromosomes, with -\log_{10}(p) on the y-axis and
genomic position on the x-axis. Each chromosome is rendered in alternating
colours, and configurable horizontal dashed lines mark genome-wide
significance thresholds.
The function is adapted from ggmanh::manhattan_plot() with the
following enhancements:
Dot-separated argument names are converted to underscores (e.g.
chr.colname\rightarrowchr_by).-
chromosomesmerges the originalchromosomeandchr.orderarguments into a single parameter for subsetting and reordering. -
highlightaccepts index vectors or R expressions (via a character string) instead of a column name. Dedicated
pt_*,label_*, andhighlight_*parameter families give granular control over point appearance, label styling, and highlight styling.-
pval_transformaccepts any function (or a character string parsed as a function) rather than a fixed log-transform toggle.
Key features include per-chromosome alternating colours, configurable significance threshold lines with labels, optional data thinning for dense SNP sets, automatic y-axis rescaling (broken-axis) when a small number of highly significant points would otherwise compress the majority of the data, and support for highlighting and labeling specific variants.
Usage
ManhattanPlotAtomic(
data,
chr_by,
pos_by,
pval_by,
label_by = NULL,
chromosomes = NULL,
pt_size = 0.75,
pt_color = NULL,
pt_alpha = alpha,
pt_shape = 19,
label_size = 3,
label_fg = NULL,
highlight = NULL,
highlight_color = NULL,
highlight_size = 1.5,
highlight_alpha = 1,
highlight_shape = 19,
preserve_position = TRUE,
chr_gap_scaling = 1,
pval_transform = "-log10",
signif = c(5e-08, 1e-05),
signif_color = NULL,
signif_rel_pos = 0.2,
signif_label = TRUE,
signif_label_size = 3.5,
signif_label_pos = c("left", "right"),
thin = NULL,
thin_n = 1000,
thin_bins = 200,
rescale = TRUE,
rescale_ratio_threshold = 5,
palette = "Dark2",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = expression("-" * log[10](p)),
...
)
Arguments
data |
A data frame. |
chr_by |
A character string specifying the column name for chromosome
identifiers. Default: |
pos_by |
A character string specifying the column name for genomic
positions (integer or numeric). Default: |
pval_by |
A character string specifying the column name for p-values
(numeric). Default: |
label_by |
A character string specifying the column name for variant
labels. Only variants with non-empty values in this column will be
labelled. Default: |
chromosomes |
A character or numeric vector specifying which
chromosomes to include and/or their display order. When |
pt_size |
A numeric value specifying the size of the points.
Default: |
pt_color |
A character string specifying a single colour for all
background (non-highlighted) points. When |
pt_alpha |
A numeric value in |
pt_shape |
A numeric value specifying the shape of the points.
Default: |
label_size |
A numeric value specifying the font size of the
variant labels. Default: |
label_fg |
A character string specifying the colour of the variant
labels. When |
highlight |
Either a numeric vector of row indices or a character
string containing an R expression (parsed via
|
highlight_color |
A character string specifying the colour of
highlighted points. When |
highlight_size |
A numeric value specifying the size of
highlighted points. Default: |
highlight_alpha |
A numeric value in |
highlight_shape |
A numeric value specifying the shape of
highlighted points. Default: |
preserve_position |
A logical value. When |
chr_gap_scaling |
A numeric scaling factor for the gap between
chromosomes. Larger values increase the gap. Default: |
pval_transform |
A function or character string that can be
evaluated to a function for transforming p-values. Default:
|
signif |
A numeric vector of significance thresholds to draw as
horizontal dashed lines. Default: |
signif_color |
A character vector of colours for the significance
threshold lines, of equal length as |
signif_rel_pos |
A numeric value between |
signif_label |
A logical value. When |
signif_label_size |
A numeric value for the font size of the
significance threshold labels. Default: |
signif_label_pos |
A character string specifying where to place
the significance threshold labels: |
thin |
A logical value indicating whether to thin dense data by
sampling points per horizontal partition. Defaults to |
thin_n |
An integer specifying the maximum number of points per
horizontal partition after thinning. Default: |
thin_bins |
An integer specifying the number of horizontal bins
for thinning. Default: |
rescale |
A logical value. When |
rescale_ratio_threshold |
A numeric threshold for triggering
y-axis rescaling. The ratio is computed as
|
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
ManhattanPlotAtomic executes the following steps:
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
signif_label_pos normalisation —
match.arg()resolvessignif_label_posto"left"or"right". -
Data preprocessing —
ggmanh::manhattan_data_preprocess()performs chromosome ordering, optional thinning (thin_npoints perthin_binshorizontal partitions), chromosome gap scaling (chr_gap_scaling), position preservation (preserve_position), and significance threshold colour assignment. Whenchromosomesis a single value, it is passed as thechromosomefilter; otherwise it is used for ordering viachr.order. -
label_by validation —
check_columns()validates and factors thelabel_bycolumn if provided. -
Chromosome colour assignment — if
highlightandhighlight_colorare both set, or ifpt_coloris given,pt_color(defaulting to"grey80") is used as the base colour for all chromosomes; otherwisepalette_this()generates distinct colours per chromosome frompalette/palcolor. -
pval_transform resolution — when a character string starting with
"-"(e.g."-log10"), the minus sign is stripped, the remainder is evaluated as a function, and the result is negated. Plain character strings are evaluated directly. The result is applied to the p-value column to producelog10pval. -
Y-axis rescaling check — when
rescale = TRUE, the ratio of the ceiling-scaled maximum to the significance-threshold jump is checked againstrescale_ratio_threshold. If the ratio exceeds the threshold, a broken y-axis is constructed viaggmanh::get_transform()that compresses the empty space between the main data and the extreme points. -
Single-chromosome branch — when only one chromosome is present, the original position column is used directly, x-axis breaks and labels use
waiver(), and the x-axis label is set to the chromosome name (or"Chromosome <name>"). -
Multi-chromosome branch — position coordinates are recalculated across chromosome boundaries via
ggmanh::calc_new_pos_(). Chromosome centre positions serve as x-axis breaks, chromosome labels are displayed, and limits span the full genomic range. -
Base plot assembly — creates a
ggplotobject withgeom_point()(chromosome-coloured dots),scale_color_manual(),scale_y_continuous()(with optional broken-axis transform),scale_x_continuous(),geom_hline()for significance thresholds, the resolved theme (with hidden grid lines and suppressed legend), andlabs(). -
Significance labels — when
signif_label = TRUE,geom_text()annotates each significance threshold at the left or right edge of the plot (controlled bysignif_label_pos), coloured bysignif_color(smallest threshold in black, others in grey by default). -
Variant labels — when
label_byis provided,ggrepel::geom_label_repel()adds labels for variants that have non-empty values in thelabel_bycolumn. Iflabel_fgis set, all labels receive that colour; otherwise each label inherits the chromosome colour of its point. -
Rescale tick marks — when y-axis rescaling is active, the axis tick style is changed (via
axis.ticks.y) and a double-equals annotation is placed at the jump point to indicate the axis break, withcoord_cartesian(clip = "off"). -
Highlight overlay — when
highlightis numeric (row indices) or a character string (R expression), the matching points are overlaid with a separategeom_point()layer styled byhighlight_*parameters, optionally in a distinct colour whenhighlight_coloris specified. -
Dimension calculation —
calculate_plot_dimensions()computes height and width from the number of chromosomes (base_height = 4.5,x_scale_factor = 0.4), and stores them asheight/widthattributes on the plot.
Network
Description
Draws a network graph from a links (edge list) data frame and an optional
nodes (vertex metadata) data frame. The graph is constructed via
igraph, laid out with igraph layout algorithms, and
rendered with ggraph. Supports directed or
undirected edges, variable link widths/linetypes/colours, node
sizes/shapes/colours/fills, community detection with enclosure marks,
automatic node labels, and a wide range of layout options.
When links (and optionally nodes) contain a
split_by column, separate sub-plots are generated for each split
level and combined via patchwork. Unlike most
other plot types, Network operates on two data frames; splitting
may affect both.
Usage
Network(
links,
nodes = NULL,
split_by = NULL,
split_by_sep = "_",
split_nodes = FALSE,
from = NULL,
from_sep = "_",
to = NULL,
to_sep = "_",
node_by = NULL,
node_by_sep = "_",
link_weight_by = 2,
link_weight_name = NULL,
link_type_by = "solid",
link_type_name = NULL,
node_size_by = 15,
node_size_name = NULL,
node_color_by = "black",
node_color_name = NULL,
node_shape_by = 21,
node_shape_name = NULL,
node_fill_by = "grey20",
node_fill_name = NULL,
link_alpha = 1,
node_alpha = 0.95,
node_stroke = 1.5,
cluster_scale = c("fill", "color", "shape"),
node_size_range = c(5, 20),
link_weight_range = c(0.5, 5),
link_arrow_offset = 20,
link_curvature = 0,
link_color_by = "from",
link_color_name = NULL,
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
link_palette = ifelse(link_color_by %in% c("from", "to"), palette, "Set1"),
link_palcolor = if (link_color_by %in% c("from", "to")) palcolor else NULL,
directed = TRUE,
layout = "circle",
cluster = "none",
add_mark = FALSE,
mark_expand = ggplot2::unit(10, "mm"),
mark_type = c("hull", "ellipse", "rect", "circle"),
mark_alpha = 0.1,
mark_linetype = 1,
add_label = TRUE,
label_size = 3,
label_fg = "white",
label_bg = "black",
label_bg_r = 0.1,
arrow = ggplot2::arrow(type = "closed", length = ggplot2::unit(0.1, "inches")),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
aspect.ratio = 1,
theme = "theme_this",
theme_args = list(),
legend.position = "right",
legend.direction = "vertical",
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
links |
A data frame containing the edge list. Must contain the
|
nodes |
An optional data frame of node metadata. When provided,
columns such as |
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
split_nodes |
A logical value. When |
from |
A character string specifying the column name in
|
from_sep |
A character string to join multiple |
to |
A character string specifying the column name in
|
to_sep |
A character string to join multiple |
node_by |
A character string specifying the column name in
|
node_by_sep |
A character string to join multiple
|
link_weight_by |
A numeric value or a character string. If
numeric, all edges receive that constant line width. If a column
name, the edge line width is mapped to that column. Default
|
link_weight_name |
A character string for the link weight legend
title. When |
link_type_by |
A character string or a column name specifying
the edge linetype. Can be |
link_type_name |
A character string for the link linetype legend
title. When |
node_size_by |
A numeric value or a character string. If
numeric, all nodes receive that constant point size. If a column
name, the size is mapped to that column. Default |
node_size_name |
A character string for the node size legend
title. When |
node_color_by |
A character string specifying the node colour.
If a colour name or hex code (e.g. |
node_color_name |
A character string for the node colour legend
title. When |
node_shape_by |
A numeric value or a character string. If
numeric, all nodes receive that constant shape (see
|
node_shape_name |
A character string for the node shape legend
title. When |
node_fill_by |
A character string specifying the node fill
colour. If a colour name or hex code (e.g. |
node_fill_name |
A character string for the node fill legend
title. When |
link_alpha |
A numeric value specifying the transparency
(alpha) of the edge lines. Between |
node_alpha |
A numeric value specifying the fill transparency
of the nodes. Only applies when |
node_stroke |
A numeric value specifying the border stroke
width of the node points. Default |
cluster_scale |
A character string specifying which node
aesthetic is overridden by cluster membership. One of
|
node_size_range |
A numeric vector of length 2 giving the
minimum and maximum node size (in ggplot2 point units) when
|
link_weight_range |
A numeric vector of length 2 giving the
minimum and maximum edge line width (in mm) when
|
link_arrow_offset |
A numeric value (in points) specifying the
offset distance for the arrow end cap from the target node.
Prevents arrow heads from overlapping the node points. Only
relevant when |
link_curvature |
A numeric value controlling the curvature of
the edges. |
link_color_by |
A character string controlling how edge colour is determined. Options:
|
link_color_name |
A character string for the edge colour legend
title. Only used when |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
link_palette |
A character string specifying the palette for
edge colours when they are mapped. When |
link_palcolor |
A character vector specifying custom colours
for the edge palette. When |
directed |
A logical value. When |
layout |
A character string or an |
cluster |
A character string specifying the community detection
algorithm. One of |
add_mark |
A logical value. When |
mark_expand |
A |
mark_type |
A character string specifying the mark geometry.
One of |
mark_alpha |
A numeric value for the fill transparency of
cluster marks. Default |
mark_linetype |
A numeric or character value specifying the
border line type of the cluster marks. Default |
add_label |
A logical value. When |
label_size |
A numeric value for the font size of node labels.
Scaled by the theme base size. Default |
label_fg |
A character string specifying the text colour of
node labels. Default |
label_bg |
A character string specifying the background colour
of node labels. Default |
label_bg_r |
A numeric value specifying the background box
radius (as a fraction of label height). Passed to
|
arrow |
A |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
seed |
The random seed to use. Default is 8525. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments. |
Value
A ggplot object (no split_by), a
patchwork object (combine = TRUE), or a named list of
ggplot objects (combine = FALSE), each with
height and width attributes in inches.
split_by workflow
When split_by is provided:
-
Column validation – The
split_bycolumn is validated inlinksviacheck_columns, force-converted to a factor, and empty levels are dropped. -
Node split – If
split_nodes = TRUEandnodesis provided, the samesplit_bycolumn is validated innodes. It must be identical in name to the linkssplit_byor an error is raised. Empty levels are also dropped. -
Data splitting – The
linksdata frame is split by thesplit_bylevels into a named list, preserving factor level order. -
Attach node splits – If
split_nodes = TRUE, thenodesdata frame is split identically. Each split's node data is attached as the"nodes"attribute on the corresponding links split. -
Dispatch to atomic –
NetworkAtomicis called for each split. Thenodesargument is passed as"@nodes"whensplit_nodes = TRUEso that it is extracted from the attribute. Iftitleis a function, it receives the split level name for dynamic title generation. -
Combination – Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list ofggplotobjects.
Examples
# Create example data
actors <- data.frame(
name = c("Alice", "Bob", "Cecil", "David", "Esmeralda"),
age = c(48, 33, 45, 34, 21),
shape = c(21, 22, 21, 22, 23),
gender = c("F", "M", "F", "M", "F")
)
relations <- data.frame(
from = c("Bob", "Cecil", "Cecil", "David", "David", "Esmeralda", "Bob", "Alice",
"Cecil", "David"),
to = c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice", "Bob", "Alice", "Cecil",
"David"),
friendship = c(4, 5, 5, 2, 1, 1, 2, 1, 3, 4),
type = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)
)
# Basic network
Network(relations, actors)
# Blank theme with no coordinate axes
Network(relations, actors, theme = "theme_blank",
theme_args = list(add_coord = FALSE))
# Mapped aesthetics with custom layout
Network(relations, actors,
link_weight_by = "friendship",
node_size_by = "age",
link_weight_name = "FRIENDSHIP",
node_fill_by = "gender",
link_color_by = "to",
link_type_by = "type",
node_color_by = "black",
layout = "circle",
link_curvature = 0.2)
# Tree layout with clustering and marks
Network(relations, actors, layout = "tree",
directed = FALSE, cluster = "fast_greedy",
add_mark = TRUE)
# Split by a column
Network(relations, actors, split_by = "type")
NetworkAtomic
Description
Core implementation for rendering a single network graph from a links
(edge list) data frame and an optional nodes (vertex metadata) data frame.
This is the workhorse behind the exported Network function –
it takes a single pair of links/nodes data frames (no
split_by support) and returns a ggplot object.
The graph is constructed via graph_from_data_frame,
laid out using igraph layout algorithms ("circle", "tree",
"grid", or any named igraph layout such as "fr" or
"kk"), and rendered with ggraph using
geom_edge_arc for links and
geom_point for nodes.
Key features include:
-
Directed / undirected graphs with optional arrow heads.
-
Link styling: variable width (weight), linetype, and colour, each constant or mapped from a column. Edge colours can follow source nodes, target nodes, or a dedicated column.
-
Node styling: variable size, shape, colour, and fill, each constant or column-mapped.
-
Community detection via igraph clustering algorithms with convex hull, ellipse, rectangle, or circle marks from
ggforce. -
Automatic labels via
geom_text_repel. -
Self-loop edges drawn as direction-sensitive arcs.
Usage
NetworkAtomic(
links,
nodes = NULL,
from = NULL,
from_sep = "_",
to = NULL,
to_sep = "_",
node_by = NULL,
node_by_sep = "_",
link_weight_by = 2,
link_weight_name = NULL,
link_type_by = "solid",
link_type_name = NULL,
node_size_by = 15,
node_size_name = NULL,
node_color_by = "black",
node_color_name = NULL,
node_shape_by = 21,
node_shape_name = NULL,
node_fill_by = "grey20",
node_fill_name = NULL,
link_alpha = 1,
node_alpha = 0.95,
node_stroke = 1.5,
cluster_scale = c("fill", "color", "shape"),
node_size_range = c(5, 20),
link_weight_range = c(0.5, 5),
link_arrow_offset = 20,
link_curvature = 0,
link_color_by = "from",
link_color_name = NULL,
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
link_palette = ifelse(link_color_by %in% c("from", "to"), palette, "Set1"),
link_palcolor = if (link_color_by %in% c("from", "to")) palcolor else NULL,
directed = TRUE,
layout = "circle",
cluster = "none",
add_mark = FALSE,
mark_expand = ggplot2::unit(10, "mm"),
mark_type = c("hull", "ellipse", "rect", "circle"),
mark_alpha = 0.1,
mark_linetype = 1,
add_label = TRUE,
label_size = 3,
label_fg = "white",
label_bg = "black",
label_bg_r = 0.1,
arrow = ggplot2::arrow(type = "closed", length = ggplot2::unit(0.1, "inches")),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
aspect.ratio = 1,
theme = "theme_this",
theme_args = list(),
legend.position = "right",
legend.direction = "vertical",
...
)
Arguments
links |
A data frame containing the edge list. Must contain the
|
nodes |
An optional data frame of node metadata. When provided,
columns such as |
from |
A character string specifying the column name in
|
from_sep |
A character string to join multiple |
to |
A character string specifying the column name in
|
to_sep |
A character string to join multiple |
node_by |
A character string specifying the column name in
|
node_by_sep |
A character string to join multiple
|
link_weight_by |
A numeric value or a character string. If
numeric, all edges receive that constant line width. If a column
name, the edge line width is mapped to that column. Default
|
link_weight_name |
A character string for the link weight legend
title. When |
link_type_by |
A character string or a column name specifying
the edge linetype. Can be |
link_type_name |
A character string for the link linetype legend
title. When |
node_size_by |
A numeric value or a character string. If
numeric, all nodes receive that constant point size. If a column
name, the size is mapped to that column. Default |
node_size_name |
A character string for the node size legend
title. When |
node_color_by |
A character string specifying the node colour.
If a colour name or hex code (e.g. |
node_color_name |
A character string for the node colour legend
title. When |
node_shape_by |
A numeric value or a character string. If
numeric, all nodes receive that constant shape (see
|
node_shape_name |
A character string for the node shape legend
title. When |
node_fill_by |
A character string specifying the node fill
colour. If a colour name or hex code (e.g. |
node_fill_name |
A character string for the node fill legend
title. When |
link_alpha |
A numeric value specifying the transparency
(alpha) of the edge lines. Between |
node_alpha |
A numeric value specifying the fill transparency
of the nodes. Only applies when |
node_stroke |
A numeric value specifying the border stroke
width of the node points. Default |
cluster_scale |
A character string specifying which node
aesthetic is overridden by cluster membership. One of
|
node_size_range |
A numeric vector of length 2 giving the
minimum and maximum node size (in ggplot2 point units) when
|
link_weight_range |
A numeric vector of length 2 giving the
minimum and maximum edge line width (in mm) when
|
link_arrow_offset |
A numeric value (in points) specifying the
offset distance for the arrow end cap from the target node.
Prevents arrow heads from overlapping the node points. Only
relevant when |
link_curvature |
A numeric value controlling the curvature of
the edges. |
link_color_by |
A character string controlling how edge colour is determined. Options:
|
link_color_name |
A character string for the edge colour legend
title. Only used when |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
link_palette |
A character string specifying the palette for
edge colours when they are mapped. When |
link_palcolor |
A character vector specifying custom colours
for the edge palette. When |
directed |
A logical value. When |
layout |
A character string or an |
cluster |
A character string specifying the community detection
algorithm. One of |
add_mark |
A logical value. When |
mark_expand |
A |
mark_type |
A character string specifying the mark geometry.
One of |
mark_alpha |
A numeric value for the fill transparency of
cluster marks. Default |
mark_linetype |
A numeric or character value specifying the
border line type of the cluster marks. Default |
add_label |
A logical value. When |
label_size |
A numeric value for the font size of node labels.
Scaled by the theme base size. Default |
label_fg |
A character string specifying the text colour of
node labels. Default |
label_bg |
A character string specifying the background colour
of node labels. Default |
label_bg_r |
A numeric value specifying the background box
radius (as a fraction of label height). Passed to
|
arrow |
A |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
... |
Not used. |
Value
A ggplot object with height and width
attributes (in inches).
Architecture
-
Column resolution – Default column names for
from,to, andnode_byare assigned whenNULL, using the first or second column of the respective data frame. Each is validated viacheck_columns; multi-column inputs are concatenated with their respective separator (from_sep,to_sep,node_by_sep) and force-converted to factors. Resolved columns are renamed to the canonical names"from","to", and"name". -
Graph construction – An
igraphobject is built viagraph_from_data_frameusing the links data frame and (optionally) the nodes data frame. Ifnodesis a string starting with"@", it is extracted from the corresponding attribute on the links object. -
Layout computation – The layout is resolved:
"circle"->layout_in_circle,"tree"->layout_as_tree,"grid"->layout_on_grid. Any other character string is prefixed with"layout_with_"and looked up in the igraph namespace (e.g."fr"->layout_with_fr). Iflayoutis already anigraph_layout_specobject it is applied directly vialayout_. -
Data extraction – Vertex and edge data frames are extracted from the igraph object via
as_data_frame. Layout coordinates are added asxandycolumns to the vertex data. -
Node aesthetic assembly – Each of
size,color,shape, andfillis resolved as either a constant value (numeric or character) or a mapping to a column of the node data. A per-aesthetic"guide"/"none"flag is tracked for legend construction. -
Link aesthetic assembly –
linewidth(weight),linetype, andcolorare resolved similarly.When
link_color_by = "from", edge colours are derived from the source node's fill (if node shape is filled, 21–25) or colour; when"to", from the target node.When
link_color_bynames a column in the links data frame (other than"from"/"to"), it is mapped directly.
If
directed = TRUE, aarrowis added andend_capis set viacircleto prevent arrow overlap with nodes. Self-loop edges receive adirectionaesthetic. -
Plot initialisation – A
ggraphplot is created withlayout = "manual"and vertex coordinates from the layout. -
Clustering and marks – When
cluster != "none", the specified igraph community-detection algorithm is run (cluster_fast_greedy,cluster_walktrap,cluster_edge_betweenness,cluster_infomap, or a custom function). Membership overrides the aesthetic specified bycluster_scale("fill","color", or"shape") with a warning that the previous setting is discarded. Ifadd_mark = TRUE, a mark enclosure (hull / ellipse / rect / circle) is drawn per cluster via the correspondingggforcegeom. -
Link rendering –
geom_edge_arcdraws the edges (with configurablelink_curvature) andgeom_edge_loophandles self-loop edges. -
Link scales – Conditional on their guide status,
scale_edge_width_continuous,scale_edge_linetype_discrete, andscale_edge_color_manual/scale_edge_color_gradientnare added for weight, linetype, and colour legends respectively. -
Node rendering –
geom_pointdraws the nodes with the assembled aesthetics. -
Node scales – Conditional scale additions:
scale_size_continuous(range fromnode_size_range),scale_color_manual,scale_shape_manual, andscale_fill_manual, each with their legend title and guide overrides. -
Labels – When
add_label = TRUE, node identifiers are rendered viageom_text_repelusinglabel_fg,label_bg, andlabel_bg_r. -
Final theme and dimensions – Coordinate expansion, axis labels, theme application, and legend positioning are applied. Plot height and width are computed via
calculate_plot_dimensionsand stored as attributes.
Pie chart
Description
Draws a pie chart illustrating the numerical proportion of each group
relative to the whole. Each slice corresponds to a level of the x-axis
variable and its angle is proportional to the y-axis value (or the
observation count when y is omitted).
The function supports count aggregation (omit y to plot
observation counts per x-category), slice labels via
ggrepel::geom_label_repel(), clockwise or counter-clockwise slice
ordering, faceting, and splitting into separate sub-plots via
split_by.
Usage
PieChart(
data,
x,
y = NULL,
label = y,
split_by = NULL,
split_by_sep = "_",
clockwise = TRUE,
facet_by = NULL,
facet_scales = "free_y",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = 1,
keep_na = FALSE,
keep_empty = FALSE,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name for the x-axis (categories). Must be character or factor. Each unique value becomes a pie slice. |
y |
A character string specifying the numeric column for the y-axis.
When |
label |
A character string specifying the column to use for slice
labels. |
split_by |
The column(s) to split the data by and produce separate
sub-plots. Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
clockwise |
A logical value. When |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default |
seed |
A numeric seed for reproducibility. Passed to
|
axes |
A character string specifying how axes should be treated across
the combined layout (passed to |
axis_titles |
A character string specifying how axis titles should be
treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should be
collected across panels. Default |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments. |
Value
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by workflow
When split_by is provided:
-
validate_common_args()validates theseedandfacet_bysettings. -
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments for all columns (x,split_by,facet_by). -
process_theme()resolves the theme function. The
xcolumn is forced to factor;yis validated.The
split_bycolumn is validated and its NA / empty levels are processed viaprocess_keep_na_empty(). It is then removed from the per-columnkeep_na/keep_emptylists.The data frame is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
PieChartAtomic()is called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
data <- data.frame(
x = factor(c("A", "B", "C", NA, "E", "F", "G", "H"), levels = LETTERS[1:8]),
y = c(10, 8, 16, 4, 6, 12, 14, 2),
group = factor(c("G1", "G1", NA, NA, "G3", "G3", "G4", "G4"),
levels = c("G1", "G2", "G3", "G4")),
facet = factor(c("F1", NA, "F3", "F4", "F1", NA, "F3", "F4"),
levels = c("F1", "F2", "F3", "F4"))
)
# Basic pie chart
PieChart(data, x = "x", y = "y")
# Keep NA and empty levels
PieChart(data, x = "x", y = "y", keep_na = TRUE, keep_empty = TRUE)
# Counter-clockwise ordering
PieChart(data, x = "x", y = "y", clockwise = FALSE)
PieChart(data, x = "x", y = "y", clockwise = FALSE,
keep_na = TRUE, keep_empty = TRUE)
# With slice labels
PieChart(data, x = "x", y = "y", label = "group")
# Faceting
PieChart(data, x = "x", y = "y", facet_by = "facet")
PieChart(data, x = "x", y = "y", facet_by = c("facet", "group"),
keep_empty = "level")
PieChart(data, x = "x", y = "y", facet_by = c("facet", "group"),
keep_empty = TRUE)
# Split into sub-plots
PieChart(data, x = "x", y = "y", split_by = "group")
# Per-split palettes
PieChart(data, x = "x", y = "y", split_by = "group",
palette = list(G1 = "Reds", G2 = "Blues", G3 = "Greens", G4 = "Purp"))
# Y from count
PieChart(data, x = "group")
# Y from count with label
PieChart(data, x = "group", label = ".y")
Atomic pie chart (internal)
Description
Core implementation for drawing a single pie chart. This is the
workhorse behind the exported PieChart function — it takes a
single data frame (no split_by support) and returns a
ggplot object. The chart maps the proportion of each x-axis
category to the angle of a pie slice using
coord_polar(), with optional faceting and
per-slice labels.
Usage
PieChartAtomic(
data,
x,
y = NULL,
label = y,
clockwise = TRUE,
keep_na = FALSE,
keep_empty = FALSE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
facet_by = NULL,
facet_scales = "free_y",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name for the x-axis (categories). Must be character or factor. Each unique value becomes a pie slice. |
y |
A character string specifying the numeric column for the y-axis.
When |
label |
A character string specifying the column to use for slice
labels. |
clockwise |
A logical value. When |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Column resolution —
xis forced to factor;yis validated (numeric, optional). -
Count aggregation — when
y = NULL, the count of observations per (x,facet_by) combination is computed as a new.ycolumn. Factor levels are preserved after aggregation. -
Label resolution — when
label = TRUE, the label column is set toy. Thelabelcolumn is then validated. -
Facet column resolution —
facet_bycolumns are validated as factors, allowing up to two columns. -
NA / empty-level handling —
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. Per-columnkeep_emptysettings are extracted forxandfacet_by. When more than one facet column is provided, theirkeep_emptyvalues must be identical. -
Clockwise ordering — when
clockwise = TRUE(default), the levels ofxare reversed so that the first slice starts from the top and proceeds clockwise. The data is then sorted by the (possibly reversed)xfactor levels. -
Position calculation — if faceted, grouping by facet variables; computes cumulative sums (
csum) and label midpoint positions (pos) for each slice. -
Colour mapping —
palette_this()assigns colours to allxlevels, includingNA(defaulting to"grey80"). -
Plot assembly — the
ggplotobject is built withgeom_col(width = 1)andcoord_polar(theta = "y")to create the circular pie layout. The fill scale usesscale_fill_manual()with per-slice colours; thedropargument is controlled bykeep_empty_x. -
Labels — when
labelis notNULL,geom_label_repel()adds text labels at the computed midpoint positions (pos). -
Dimension calculation —
calculate_plot_dimensions()computes plot height and width fromaspect.ratioand legend metrics. The resultingheight/widthattributes are stored on theggplotobject. -
Faceting —
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided, respecting thekeep_emptysetting for facet variables.
QQ/PP plot
Description
Produces a quantile-quantile (QQ) plot or probability-probability (PP) plot to compare the empirical distribution of a numeric variable against a theoretical distribution (default: standard normal). The function delegates to the qqplotr package for the underlying statistics and rendering.
Key features:
-
QQ and PP modes – switch between quantile-quantile and probability-probability displays via
type. -
Confidence bands – overlay one or more confidence bands (pointwise, KS, Tukey simultaneous, or bootstrap) with custom fill colours and alpha.
-
Reference line – a diagonal reference line (QQ) or diagonal probability line (PP) for comparison.
-
Distribution fitting – compare against any distribution supported by qqplotr (normal, exponential, uniform, etc.) by passing
distributionanddparamsinside theband,line, andpointlists. -
Detrending – enable
detrend = TRUEinside the argument lists to remove the reference line and visualise only deviations (flat PP plot centred at zero). -
Splitting – use
split_byto produce separate QQ/PP plots for different groups, combined into a single layout.
Usage
QQPlot(
data,
val,
val_trans = NULL,
type = c("qq", "pp"),
split_by = NULL,
split_by_sep = "_",
band = NULL,
line = list(),
point = list(),
fill_name = "Bands",
band_alpha = 0.5,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlim = NULL,
ylim = NULL,
xlab = ifelse(type == "qq", "Theoretical Quantiles", "Probability Points"),
ylab = ifelse(type == "qq", "Sample Quantiles", "Cumulative Probability"),
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
val |
A character string naming the numeric column whose distribution is compared against the theoretical distribution. |
val_trans |
A transformation function applied to the |
type |
A character string specifying the plot type. Either
|
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
band |
A list of arguments passed to |
line |
A list of arguments passed to |
point |
A list of arguments passed to |
fill_name |
A character string for the fill legend title used
when bands are present. Default: |
band_alpha |
A numeric value in |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlim |
A numeric vector of length 2 specifying the x-axis limits.
Default: |
ylim |
A numeric vector of length 2 specifying the y-axis limits.
Default: |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
seed |
The random seed to use. Default is 8525. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments. |
Value
A ggplot object (single plot), a patchwork object
(combined split plots), or a named list of ggplot objects
(when combine = FALSE), each with height and
width attributes in inches.
split_by Workflow
When split_by is provided:
-
Common arg validation –
validate_common_args()checks theseedandfacet_byconstraints. -
Theme processing –
process_theme()resolves thethemestring or function. -
split_by column resolution –
check_columns()validates thesplit_bycolumn(s) withforce_factor = TRUE. Multiple columns are concatenated withsplit_by_sep. -
Data splitting – the data frame is split by
split_bylevels (droplevels applied, level order preserved). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...". -
Per-split parameter resolution –
check_palette(),check_palcolor(), andcheck_legend()resolve per-splitpalette,palcolor,legend.position, andlegend.direction. -
Dispatch per split –
QQPlotAtomic()is called for each split level. Iftitleis a function, it receives the split level name and generates a dynamic title; otherwise the level name is used as the default title. -
Combination – results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list (whencombine = FALSE).
Examples
set.seed(8525)
data <- data.frame(norm = rnorm(100))
# Basic QQ plot with default confidence band
QQPlot(data, val = "norm", band = TRUE)
# Multiple confidence bands with custom fill labels
QQPlot(data, val = "norm", band = list(
list(bandType = "ks", mapping = ggplot2::aes(fill = "KS"), alpha = 0.3),
list(bandType = "ts", mapping = ggplot2::aes(fill = "TS")),
list(bandType = "pointwise", mapping = ggplot2::aes(fill = "Normal")),
list(bandType = "boot", mapping = ggplot2::aes(fill = "Bootstrap"))
), band_alpha = 0.6)
# Compare against exponential distribution
data(airquality, package = "datasets")
di <- "exp"
dp <- list(rate = 2)
QQPlot(airquality, val = "Ozone",
band = list(distribution = di, dparams = dp),
line = list(distribution = di, dparams = dp),
point = list(distribution = di, dparams = dp)
)
# Detrended QQ plot: deviations from the reference line
de <- TRUE
QQPlot(airquality, val = "Ozone",
band = list(distribution = di, dparams = dp, detrend = de),
line = list(distribution = di, dparams = dp, detrend = de),
point = list(distribution = di, dparams = dp, detrend = de)
)
# PP plot (probability-probability)
QQPlot(data, val = "norm", type = "pp", band = TRUE)
# PP plot with shifted/scaled normal distribution
dp <- list(mean = 2, sd = 2)
QQPlot(data, val = "norm", type = "pp",
band = list(dparams = dp),
point = list(dparams = dp))
# PP plot with custom intercept/slope line
QQPlot(data, val = "norm", type = "pp", band = TRUE,
line = list(ab = c(.2, .5)))
# Detrended PP plot with axis limits
di <- "exp"
dp <- list(rate = .022)
de <- TRUE
QQPlot(airquality, val = "Ozone", type = "pp",
band = list(distribution = di, detrend = de, dparams = dp),
line = list(detrend = de),
point = list(distribution = di, detrend = de, dparams = dp),
ylim = c(-.5, .5)
)
Atomic QQ/PP plot
Description
Core implementation for drawing a single quantile-quantile (QQ) or
probability-probability (PP) plot. This is the internal workhorse
dispatched by the exported QQPlot function – it takes a
single data frame (no split_by support) and returns a
ggplot object. The function compares the empirical distribution
of a numeric variable against a theoretical distribution (default:
standard normal) via the qqplotr package.
Two plot types are supported via the type parameter:
-
QQ plot (
type = "qq", the default) – plots sample quantiles against theoretical quantiles. Deviations from the reference line indicate departures from the assumed distribution (skewness, heavy tails, outliers). -
PP plot (
type = "pp") – plots empirical cumulative probability against theoretical cumulative probability. PP plots are more sensitive to deviations in the centre of the distribution, while QQ plots are more sensitive at the tails.
The function can overlay confidence bands (band) around
the reference line using several methods (pointwise confidence intervals,
Kolmogorov-Smirnov, Tukey's simultaneous intervals, or bootstrap).
Multiple bands can be combined and each receives a separate fill colour
from the palette.
Usage
QQPlotAtomic(
data,
val,
val_trans = NULL,
type = c("qq", "pp"),
band = NULL,
line = list(),
point = list(),
fill_name = "Bands",
band_alpha = 0.5,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
seed = 8525,
xlim = NULL,
ylim = NULL,
xlab = ifelse(type == "qq", "Theoretical Quantiles", "Probability Points"),
ylab = ifelse(type == "qq", "Sample Quantiles", "Cumulative Probability"),
...
)
Arguments
data |
A data frame. |
val |
A character string naming the numeric column whose distribution is compared against the theoretical distribution. |
val_trans |
A transformation function applied to the |
type |
A character string specifying the plot type. Either
|
band |
A list of arguments passed to |
line |
A list of arguments passed to |
point |
A list of arguments passed to |
fill_name |
A character string for the fill legend title used
when bands are present. Default: |
band_alpha |
A numeric value in |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
seed |
A numeric value for the random seed used internally.
Default: |
xlim |
A numeric vector of length 2 specifying the x-axis limits.
Default: |
ylim |
A numeric vector of length 2 specifying the y-axis limits.
Default: |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches).
Architecture
QQPlotAtomic executes the following steps:
-
ggplot dispatch – selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Type validation –
match.arg()resolvestypeto"qq"or"pp". -
Input validation –
stopifnot()checks thatbandisTRUE, a list, orNULL;lineandpointare lists orNULL; andxlim/ylimare numeric vectors of length 2 orNULL. -
Column resolution –
check_columns()validates thevalcolumn. -
Value transformation – when
val_transis provided, it is applied to thevalcolumn (e.g. log-transform). -
Base ggplot – initialises
ggplot(data, aes(sample = !!sym(val))). Thesampleaesthetic is the standard interface for qqplotr. -
Band rendering – when
bandis notNULL:Selects the band stat function:
qqplotr::stat_qq_bandfor QQ plots orqqplotr::stat_pp_bandfor PP plots.Converts
band = TRUEto an empty list (default arguments).Normalises a single band (non-list or named list) into a list-of-lists format.
Iterates over bands, assigning each a default fill aesthetic (
"Band_1","Band_2", ..., up to a maximum of 10). The user can override the fill mapping viamappinginside each band's argument list.Sets
alphaper band, falling back to theband_alphaparameter.Adds each band to the plot via
do_call(band_fn, bnd).
-
Legend position resolution – if no bands were rendered or all bands use default
"Band_"names, the legend defaults to"none"(whenlegend.positionis awaiver); otherwise defaults to"right". -
Reference line – when
lineis notNULL, addsqqplotr::stat_qq_line(QQ) orqqplotr::stat_pp_line(PP) viado_call(). -
Points – when
pointis notNULL, addsqqplotr::stat_qq_point(QQ) orqqplotr::stat_pp_point(PP) viado_call(). -
Fill colour scale – when bands are present,
scale_fill_manual()is added with colours resolved viapalette_this()using the band names,palette,palcolor, andpalreverse. The legend title is set tofill_name. -
Axis limits –
ggplot2::xlim()andggplot2::ylim()are applied ifxlimorylimare set. -
Labels and theme –
labs(title, subtitle, x, y)with fallback tovalfor axis labels;do_call(theme, theme_args);ggplot2::theme()withaspect.ratio,panel.grid.major(grey80, dashed),legend.position, andlegend.direction. -
Dimension calculation –
calculate_plot_dimensions()withbase_height = 4.5,aspect.ratio, and legend metrics (number of bands, band name character width). -
Faceting –
facet_plot()appliesfacet_wrap/facet_gridiffacet_byis provided.
ROC curve
Description
Draws one or more Receiver Operating Characteristic (ROC) curves for
evaluating binary classifier performance. The function wraps
ROCCurveAtomic with split_by handling, providing the
ability to generate separate ROC curves per split level and combine them
via wrap_plots.
Usage
ROCCurve(
data,
truth_by,
score_by,
pos_label = NULL,
split_by = NULL,
split_by_sep = "_",
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
x_axis_reverse = FALSE,
percent = FALSE,
ci = NULL,
n_cuts = 0,
cutoffs_at = NULL,
cutoffs_labels = NULL,
cutoffs_accuracy = 0.001,
cutoffs_pt_size = 5,
cutoffs_pt_shape = 4,
cutoffs_pt_stroke = 1,
cutoffs_labal_fg = "black",
cutoffs_label_size = 4,
cutoffs_label_bg = "white",
cutoffs_label_bg_r = 0.1,
show_auc = c("auto", "none", "legend", "plot"),
auc_accuracy = 0.01,
auc_size = 4,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = ifelse(x_axis_reverse, "Specificity", "1 - Specificity"),
ylab = "Sensitivity",
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
truth_by |
A character string naming the column that contains the true class labels (binary outcome, 0/1 or TRUE/FALSE). |
score_by |
A character vector of column names containing the predicted
scores (classifier output values). When multiple columns are provided, each
column becomes a separate ROC curve grouped by a |
pos_label |
A character string specifying the positive class label in
|
split_by |
The column(s) to split the data by and produce separate
ROC curve plots for each level. The |
split_by_sep |
A character string used to separate concatenated
|
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string to use as the legend title for the
ROC curve groups. When NULL (default), the |
x_axis_reverse |
A logical value. If TRUE, the x-axis is reversed (from
1 to 0), displaying specificity instead of 1 - specificity. The x-axis
label automatically changes to |
percent |
A logical value. If TRUE, the x and y axes are displayed as percentages (0 to 100). Default: FALSE. |
ci |
A list of arguments passed to |
n_cuts |
An integer specifying the number of evenly-spaced quantile-based
cutoff points to annotate on the ROC curve. Quantiles are computed from the
|
cutoffs_at |
A vector of user-supplied cutoff values to annotate as
points on the ROC curve. When non-NULL, overrides
|
cutoffs_labels |
A character vector of user-supplied labels for the
cutoff points. Must be the same length as |
cutoffs_accuracy |
A numeric value controlling the rounding precision of
automatically generated cutoff labels. Default: |
cutoffs_pt_size |
A numeric value specifying the size of the cutoff
point markers. Default: |
cutoffs_pt_shape |
A numeric value specifying the shape of the cutoff
point markers. Default: |
cutoffs_pt_stroke |
A numeric value specifying the stroke width of the
cutoff point markers. Default: |
cutoffs_labal_fg |
A character string specifying the text colour of
the cutoff labels. Default: |
cutoffs_label_size |
A numeric value specifying the font size of the
cutoff labels. Default: |
cutoffs_label_bg |
A character string specifying the background colour
of the cutoff labels. Default: |
cutoffs_label_bg_r |
A numeric value specifying the background radius
of the cutoff labels (passed to |
show_auc |
A character string specifying the display mode for AUC values:
|
auc_accuracy |
A numeric value controlling the rounding precision of
AUC values in labels. Default: |
auc_size |
A numeric value specifying the font size of AUC labels when
displayed on the plot. Default: |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
combine |
A logical value. When TRUE (default), the list of per-split
plots is combined into a single |
nrow, ncol |
Integer values specifying the number of rows and columns
in the combined plot layout. Passed to |
byrow |
A logical value. If TRUE (default), the combined layout is
filled row-wise. Passed to |
seed |
A numeric seed for reproducibility. Default: |
axes |
A character string specifying how axes are treated across the
combined layout. Passed to |
axis_titles |
A character string specifying how axis titles are treated
across the combined layout. Defaults to |
guides |
A character string specifying how legends are collected across
panels in the combined layout. Passed to |
design |
A custom layout specification for the combined plot. Passed
to |
... |
Additional arguments. |
Details
Key features:
-
Multiple classifiers — compare several prediction scores side-by-side by providing multiple
score_bycolumns. -
AUC display — area under the curve values shown on the plot or in the legend, with configurable precision.
-
Optimal cutoffs — identify and annotate optimal cutoff points using any of the 30+ methods from the
OptimalCutpointspackage, or supply custom numeric thresholds. -
Confidence intervals — add ROC confidence bands via
plotROC::geom_rocci(). -
Axis orientation — reverse x-axis to show specificity or display axes as percentages.
-
Splitting and faceting — split data into sub-plots via
split_byor facet within a single plot viafacet_by.
Value
A patchwork object (when combine = TRUE) with
attr(p, "auc") and attr(p, "cutoffs") data frames
containing aggregated AUC values and cutoff information across all
splits. When combine = FALSE, returns a named list of
ggplot objects, each with their own attr(p[[i]], "auc")
and attr(p[[i]], "cutoffs").
split_by Workflow
When split_by is provided, the following pipeline executes:
-
Validation —
validate_common_args()checks the random seed andfacet_byconfiguration. -
Column resolution —
check_columns()resolvessplit_by(force_factor, allow_multi, concat_multi). -
Data splitting — Unused factor levels in
split_byare dropped viadroplevels(), and the data is split bysplit_bylevels (preserving factor level order). Ifsplit_byis NULL, the data is wrapped in a single-element list named"...". -
Per-split resolution —
check_palette(),check_palcolor(), andcheck_legend()resolve per-split palette, colour, legend.position, and legend.direction overrides. -
Per-split dispatch — For each split:
Title resolution: if
titleis a function, it receives the split level name; otherwisetitle %||% split_levelis used.The
split_bycolumn is removed from the per-split data frame to avoid conflicts with the ROC analysis.-
ROCCurveAtomic()is called with the per-split palette, palcolor, legend.position, and legend.direction.
-
Combination —
combine_plots()assembles the list of plots viapatchwork::wrap_plots, honouringnrow/ncol/byrow/design. -
AUC / cutoff collection — When
combine = TRUE, the per-splitaucandcutoffsattributes are collected into combined data frames with asplit_bycolumn identifying the source split, and stored asattr(p, "auc")andattr(p, "cutoffs").
Examples
set.seed(8525)
D.ex <- rbinom(200, size = 1, prob = .5)
M1 <- rnorm(200, mean = D.ex, sd = .65)
M2 <- rnorm(200, mean = D.ex, sd = 1.5)
gender <- c("Male", "Female")[rbinom(200, 1, .49) + 1]
data <- data.frame(D = D.ex, D.str = c("Healthy", "Ill")[D.ex + 1],
gender = gender, M1 = M1, M2 = M2)
# --- Basic ROC curve ---
ROCCurve(data, truth_by = "D", score_by = "M1")
# --- Will warn about the positive label ---
ROCCurve(data, truth_by = "D.str", score_by = "M1")
# --- Decreasing direction ---
ROCCurve(data, truth_by = "D", score_by = "M1", increasing = FALSE)
# --- Multiple ROC curves (multiple classifiers) ---
ROCCurve(data, truth_by = "D", score_by = c("M1", "M2"), group_name = "Method")
# --- Grouping by a column ---
ROCCurve(data, truth_by = "D", score_by = "M1", group_by = "gender", show_auc = "plot")
# --- Reverse x-axis and display as percentages ---
ROCCurve(data, truth_by = "D", score_by = "M1", x_axis_reverse = TRUE, percent = TRUE)
# --- Custom n_cuts and single colour ---
ROCCurve(data, truth_by = "D", score_by = "M1", n_cuts = 10, palcolor = "black")
# --- Add confidence intervals ---
ROCCurve(data, truth_by = "D", score_by = "M1", ci = list(sig.level = .01))
# --- Facet by a column ---
ROCCurve(data, truth_by = "D", score_by = "M1", facet_by = "gender")
# --- Show cutoffs ---
ROCCurve(data, truth_by = "D", score_by = "M1", cutoffs_at = c(0, "ROC01", "SpEqualSe"))
# --- Split by a column ---
p <- ROCCurve(data, truth_by = "D", score_by = "M1", split_by = "gender",
cutoffs_at = c(0.2, "MaxSpSe"))
p
# Retrieve the AUC values
attr(p, "auc")
# Retrieve the cutoffs
attr(p, "cutoffs")
Atomic ROC curve (internal)
Description
Core implementation for drawing a single Receiver Operating Characteristic
(ROC) curve. This is the internal workhorse behind the exported
ROCCurve function. It takes a single data frame (no
split_by support) and returns a ggplot object.
Usage
ROCCurveAtomic(
data,
truth_by,
score_by,
pos_label = NULL,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
x_axis_reverse = FALSE,
percent = FALSE,
ci = NULL,
n_cuts = 0,
cutoffs_at = NULL,
cutoffs_labels = NULL,
cutoffs_accuracy = 0.01,
cutoffs_pt_size = 5,
cutoffs_pt_shape = 4,
cutoffs_pt_stroke = 1,
cutoffs_labal_fg = "black",
cutoffs_label_size = 4,
cutoffs_label_bg = "white",
cutoffs_label_bg_r = 0.1,
show_auc = c("auto", "none", "legend", "plot"),
auc_accuracy = 0.01,
auc_size = 4,
increasing = TRUE,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = ifelse(x_axis_reverse, "Specificity", "1 - Specificity"),
ylab = "Sensitivity",
...
)
Arguments
data |
A data frame with the truth and score columns. See https://CRAN.R-project.org/package=plotROC for the expected format. |
truth_by |
A character string naming the column that contains the true class labels (binary outcome, 0/1 or TRUE/FALSE). |
score_by |
A character vector of column names containing the predicted
scores (classifier output values). When multiple columns are provided, each
column becomes a separate ROC curve grouped by a |
pos_label |
A character string specifying the positive class label in
|
group_by |
A character vector of column names to group the ROC curve by.
Each unique combination of group values renders a separate ROC curve.
When |
group_by_sep |
A character string used to separate concatenated
|
group_name |
A character string to use as the legend title for the
ROC curve groups. When NULL (default), the |
x_axis_reverse |
A logical value. If TRUE, the x-axis is reversed (from
1 to 0), displaying specificity instead of 1 - specificity. The x-axis
label automatically changes to |
percent |
A logical value. If TRUE, the x and y axes are displayed as percentages (0 to 100). Default: FALSE. |
ci |
A list of arguments passed to |
n_cuts |
An integer specifying the number of evenly-spaced quantile-based
cutoff points to annotate on the ROC curve. Quantiles are computed from the
|
cutoffs_at |
A vector of user-supplied cutoff values to annotate as
points on the ROC curve. When non-NULL, overrides
|
cutoffs_labels |
A character vector of user-supplied labels for the
cutoff points. Must be the same length as |
cutoffs_accuracy |
A numeric value controlling the rounding precision of
automatically generated cutoff labels. Default: |
cutoffs_pt_size |
A numeric value specifying the size of the cutoff
point markers. Default: |
cutoffs_pt_shape |
A numeric value specifying the shape of the cutoff
point markers. Default: |
cutoffs_pt_stroke |
A numeric value specifying the stroke width of the
cutoff point markers. Default: |
cutoffs_labal_fg |
A character string specifying the text colour of
the cutoff labels. Default: |
cutoffs_label_size |
A numeric value specifying the font size of the
cutoff labels. Default: |
cutoffs_label_bg |
A character string specifying the background colour
of the cutoff labels. Default: |
cutoffs_label_bg_r |
A numeric value specifying the background radius
of the cutoff labels (passed to |
show_auc |
A character string specifying the display mode for AUC values:
|
auc_accuracy |
A numeric value controlling the rounding precision of
AUC values in labels. Default: |
auc_size |
A numeric value specifying the font size of AUC labels when
displayed on the plot. Default: |
increasing |
A logical value. If TRUE (default), higher scores indicate the positive class; if FALSE, lower scores indicate the positive class. Controls the direction of comparison in the ROC analysis. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
... |
Additional arguments. |
Details
The function produces an ROC curve using plotROC::geom_roc(), with
the following capabilities:
-
Multiple classifiers —
score_byaccepts multiple column names, automatically pivoting them into a grouped format so several prediction scores can be compared on a single plot. -
AUC calculation — area under the curve is computed via
plotROC::calc_auc()and displayed either on the plot or in the legend, controlled byshow_auc. -
Cutoff annotation — user-specified cutoffs (numeric score thresholds or named optimal-cutoff methods from the
OptimalCutpointspackage) are rendered as markers with labels, usingggrepel::geom_text_repel()for label placement. -
Confidence intervals — optional ROC confidence bands via
plotROC::geom_rocci(). -
Axis flexibility — supports reversed x-axis (displaying specificity) and percent-scaled axes.
Value
A ggplot object with height and width
attributes (in inches) attached, plus attr(p, "auc") and
attr(p, "cutoffs") data frames.
Architecture
-
show_auc resolution —
match.arg()resolvesshow_aucto one of"auto","none","legend", or"plot". -
Column validation —
check_columns()validatestruth_by(single column),score_by(multiple allowed), andgroup_by(factor, multi-column concatenated). An error is raised ifgroup_byis provided alongside multiplescore_bycolumns. -
Positive label encoding — Converts
truth_byto binary numeric (0/1) with three paths:-
pos_labelprovided: re-factor withpos_labelas the last level, then convert. -
truth_byis a factor: warn that the last level is treated as positive, then convert. Non-numeric, non-factor: coerce to factor, warn, then convert.
-
-
Multi-score_by expansion — When
score_bycontains multiple columns,tidyr::pivot_longer()reshapes into a single.scorecolumn with a.groupidentifier, which becomes thegroup_byvariable. -
ggplot dispatch — Selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Dummy group insertion — When
group_by = NULL, creates a synthetic..groupcolumn (constant"") so the curve still renders. The legend is suppressed ("none"). -
Auto AUC placement — When
show_auc = "auto", single-group or faceted plots place AUC on the plot; multi-group plots place it in the legend. -
Base ROC geometry —
plotROC::geom_roc()withaes(d = truth, m = score, color = group), controlling direction via theincreasingparameter. -
AUC calculation — Temporarily facets via
facet_plot(), then computes per-group (and per-facet) AUC values viaplotROC::calc_auc(). -
Cutoff computation —
get_cutoffs_data()combinesgroup_byandfacet_bycolumns into a.catidentifier and computes per-category cutoff data, supporting both numeric thresholds and namedOptimalCutpointsmethods. -
Cutoff rendering — When cutoff data is non-NULL, splits the
.catcolumn back into group/facet columns and addsgeom_point()(markers) andgeom_text_repel()(labels) with configurable size, shape, stroke, colour, and background styling. -
Confidence intervals — When
ciis non-NULL,plotROC::geom_rocci()is added with the provided arguments. -
AUC display — Three modes:
-
"plot":geom_text()places AUC labels at a corner position determined byincreasingandx_axis_reverse. -
"legend": AUC values are appended to thescale_color_manual()labels (with per-facet prefixes when faceting is active). -
"none": group level names are used as-is.
-
-
Diagonal reference —
geom_abline()draws the no-discrimination line (y = x, or y = -x when x-axis is reversed) as a dashed grey line. -
Color scale —
scale_color_manual()assigns palette-derived colours viapalette_this(), with AUC-augmented labels whenshow_auc = "legend". -
Axis formatting — Percent labels on y-axis (and x-axis) when
percent = TRUE. X-axis reversed (1 to 0) whenx_axis_reverse = TRUE, changing the axis label to"Specificity". -
Labels and theme —
labs()sets title, subtitle, x, and y labels. The theme, aspect ratio, legend position/direction, and dashed grid lines are applied. -
Dimension calculation —
calculate_plot_dimensions()computesheightandwidthattributes frombase_height = 4.5, aspect ratio, and legend metrics. -
Attribute storage —
aucandcutoffsdata frames are stored asattr(p, "auc")andattr(p, "cutoffs")for retrieval by the exported wrapper. -
Faceting —
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided.
Radar plot / Spider plot
Description
Draws a radar chart (concentric circular grid) or spider chart (polygonal grid) displaying multivariate data in a two-dimensional polar coordinate system. Each x-axis category is placed at an evenly spaced angular position around the chart, and numeric values are plotted along the radial axis.
The function supports count aggregation (omit y to
plot observation counts), proportion scaling (via
scale_y), per-group colour control, faceting, and splitting
into separate sub-plots via split_by.
SpiderPlot is an alias that renders the same data with
polygonal grid lines (spider chart style) by using
polygon = TRUE.
SpiderPlot is a variant of RadarPlot that renders the chart with
straight polygonal grid lines (spider chart) instead of concentric
circles. Internally, it calls RadarPlotAtomic with
polygon = TRUE but is otherwise identical to
RadarPlot in behaviour and parameters.
Usage
RadarPlot(
data,
x,
x_sep = "_",
group_by = NULL,
group_by_sep = "_",
y = NULL,
group_name = NULL,
groups = NULL,
scale_y = c("group", "global", "x", "none"),
y_min = 0,
y_max = NULL,
y_nbreaks = 4,
bg_color = "grey80",
bg_alpha = 0.1,
fill = TRUE,
linewidth = 1,
pt_size = 4,
max_charwidth = 16,
split_by = NULL,
split_by_sep = "_",
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
alpha = 0.2,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
keep_na = FALSE,
keep_empty = FALSE,
title = NULL,
subtitle = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
SpiderPlot(
data,
x,
x_sep = "_",
group_by = NULL,
group_by_sep = "_",
y = NULL,
group_name = NULL,
groups = NULL,
scale_y = c("group", "global", "x", "none"),
y_min = 0,
y_max = NULL,
y_nbreaks = 4,
bg_color = "grey80",
bg_alpha = 0.1,
fill = TRUE,
linewidth = 1,
pt_size = 4,
max_charwidth = 16,
split_by = NULL,
split_by_sep = "_",
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
alpha = 0.2,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
keep_na = FALSE,
keep_empty = FALSE,
title = NULL,
subtitle = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
x_sep |
A character string used to join multiple |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
group_name |
A character string used as the colour/fill legend
title. When |
groups |
A character vector of group values (in the
|
scale_y |
How should the radial axis be scaled? Default is
|
y_min |
A numeric value setting the minimum of the radial
axis. Default |
y_max |
A numeric value setting the maximum of the radial
axis. When |
y_nbreaks |
A numeric value for the number of breaks
(concentric grid lines) on the radial axis. Default |
bg_color |
A character string specifying the background fill
colour. Default |
bg_alpha |
A numeric value for the transparency of the
background fill. Default |
fill |
A logical value. When |
linewidth |
A numeric value for the width of the polygon
outline lines. Default |
pt_size |
A numeric value for the size of the data point
markers. Default |
max_charwidth |
A numeric value for the maximum character
width of x-axis labels before wrapping. Default |
split_by |
The column(s) to split the data by and produce
separate sub-plots. Multiple columns are concatenated with
|
split_by_sep |
A character string to separate concatenated
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
seed |
A numeric seed for reproducibility. Passed to
|
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined
layout (passed to |
byrow |
Logical; fill the combined layout by row. Default
|
axes |
A character string specifying how axes should be
treated across the combined layout (passed to
|
axis_titles |
A character string specifying how axis titles
should be treated across the combined layout. Defaults to
|
guides |
A character string specifying how guides (legends)
should be collected across panels (passed to
|
design |
A custom layout design for the combined plot (passed
to |
... |
Additional arguments. |
Value
A ggplot object (when combine = TRUE and
split_by is NULL), a patchwork object (when
combine = TRUE and split_by is provided), or a named
list of ggplot objects (when combine = FALSE), each
with height and width attributes in inches.
A ggplot object (when combine = TRUE and
split_by is NULL), a patchwork object (when
combine = TRUE and split_by is provided), or a named
list of ggplot objects (when combine = FALSE), each
with height and width attributes in inches.
split_by Workflow
When split_by is provided:
-
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments for all relevant columns (x,split_by,group_by,facet_by). The
split_bycolumn is validated and its NA / empty levels are processed viaprocess_keep_na_empty(). It is then removed from the per-columnkeep_na/keep_emptylists.The data frame is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
RadarPlotAtomic()is called for each split withpolygon = FALSE. Iftitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
set.seed(8525)
# --- Radar chart with observation counts ---
data <- data.frame(
x = factor(
c(rep("A", 20), rep("B", 30), rep(NA, 30), rep("D", 40), rep("E", 50)),
levels = LETTERS[1:5]
),
group = factor(
sample(c("G1", NA, "G3", "G4"), 170, replace = TRUE),
levels = c("G1", "G2", "G3", "G4")
)
)
# Basic radar chart
RadarPlot(data, x = "x")
# Keep NA and empty factor levels
RadarPlot(data, x = "x", keep_na = TRUE, keep_empty = TRUE)
# Custom background colour
RadarPlot(data, x = "x", bg_color = "lightpink")
# Raw counts (no proportion scaling)
RadarPlot(data, x = "x", scale_y = "none")
# Grouped by a variable
RadarPlot(data, x = "x", group_by = "group", keep_na = TRUE)
# Faceted by a variable
RadarPlot(data, x = "x", facet_by = "group")
# Spider chart variant (polygonal grid)
SpiderPlot(data, x = "x")
SpiderPlot(data, x = "x", group_by = "group")
# --- Radar chart with explicit y values ---
data <- data.frame(
x = rep(LETTERS[1:5], 2),
y = c(1, 3, 6, 4, 2, 5, 7, 8, 9, 10),
group = rep(c("G1", "G2"), each = 5)
)
# Grouped radar with raw values
RadarPlot(data, x = "x", y = "y", scale_y = "none", group_by = "group")
# Faceted radar
RadarPlot(data, x = "x", y = "y", facet_by = "group")
# Split into separate sub-plots
RadarPlot(data, x = "x", y = "y", split_by = "group")
# Per-split palettes
RadarPlot(data, x = "x", y = "y", split_by = "group",
palette = c(G1 = "Set1", G2 = "Paired"))
Atomic radar/spider plot (internal)
Description
Core implementation for drawing a single radar (or spider) chart. This
is the workhorse behind the exported RadarPlot and
SpiderPlot functions — it takes a single data frame
(no split_by support) and returns a ggplot object.
Radar charts display multivariate data on a two-dimensional polar
coordinate system where each variable (x-axis category) is placed
along a radial axis evenly spaced around the circle. The data values
are connected by lines forming a polygon (or multiple polygons when
group_by is provided). When polygon = FALSE (the
default) the grid is rendered as concentric circles (classic radar
chart); when polygon = TRUE straight polygonal grid lines are
used (spider chart variant).
The polar coordinate system is implemented via a local
coord_radar() helper that extends
ggplot2::CoordPolar with is_linear = TRUE, allowing
discrete x-axis positions to be mapped to evenly spaced angular
coordinates.
Usage
RadarPlotAtomic(
data,
x,
x_sep = "_",
group_by = NULL,
group_by_sep = "_",
y = NULL,
group_name = NULL,
groups = NULL,
scale_y = c("group", "global", "x", "none"),
y_min = 0,
y_max = NULL,
y_nbreaks = 4,
polygon = FALSE,
fill = TRUE,
linewidth = 1,
pt_size = 4,
max_charwidth = 16,
bg_color = "grey80",
bg_alpha = 0.1,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
alpha = 0.2,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
keep_na = FALSE,
keep_empty = FALSE,
title = NULL,
subtitle = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data
frame to plot on the x-axis (the radial categories). Must be
character or factor. Multiple columns can be provided; they are
concatenated with |
x_sep |
A character string used to join multiple |
group_by |
A character vector of column names to group the
data into separate filled polygons. Each unique combination
becomes a distinct polygon layer. Multiple columns are
concatenated with |
group_by_sep |
A character string used to join multiple
|
y |
A character string specifying the numeric column for the
radial axis. When |
group_name |
A character string used as the colour/fill legend
title. When |
groups |
A character vector of group values (in the
|
scale_y |
How should the radial axis be scaled? Default is
|
y_min |
A numeric value setting the minimum of the radial
axis. Default |
y_max |
A numeric value setting the maximum of the radial
axis. When |
y_nbreaks |
A numeric value for the number of breaks
(concentric grid lines) on the radial axis. Default |
polygon |
A logical value. When |
fill |
A logical value. When |
linewidth |
A numeric value for the width of the polygon
outline lines. Default |
pt_size |
A numeric value for the size of the data point
markers. Default |
max_charwidth |
A numeric value for the maximum character
width of x-axis labels before wrapping. Default |
bg_color |
A character string specifying the background fill
colour. Default |
bg_alpha |
A numeric value for the transparency of the
background fill. Default |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
Column resolution —
x,y,group_by, andfacet_byare validated and transformed viacheck_columns. Multi-column inputs forxandgroup_byare concatenated usingx_sepandgroup_by_sep. -
Group setup — When
group_byisNULL, a dummy.groupfactor is created so polygons still draw. The legend is suppressed. Whengroupsis provided, data is filtered to only those group levels. -
Count aggregation — When
y = NULL, the count of observations in each unique (x,group_by,facet_by) combination is computed. Factor levels are preserved after aggregation. -
Proportion scaling — The
scale_yargument controls y-value normalisation:"group"scales within each group,"global"within each facet (or the whole dataset),"x"within each x category, and"none"leaves values raw. Percent labels are used for scaled modes. -
NA / empty-level handling —
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. Per-columnkeep_emptysettings forx,group_by, andfacet_byare extracted; facet columns must share the same value. -
Coordinate setup — The local
coord_radar()creates aCoordPolarsubclass withis_linear = TRUE, placing discrete x positions at evenly spaced angles. -
Y-axis range —
y_min,y_max, andy_nbreaksdetermine the radial axis limits and the number of concentric grid lines. -
Colour mapping —
palette_this()assigns colours to allgroup_bylevels, includingNA(defaulting to"grey80"). -
Background layer — When
polygon = TRUE, a polygonal background fills the area betweeny_minandy_max. Whenpolygon = FALSE, a smooth circular background is interpolated via 360 sample points. -
Radial grid lines —
geom_path()draws radial lines fromy_mintoy_maxat each x-axis position, respecting facets. -
Polygon grid — When
polygon = TRUE, concentric polygonal grid lines are drawn at each break level viageom_polygon(). -
Data rendering —
geom_polygon()draws the filled (or unfilled) polygons for each group.geom_point()adds points at each observation. Radial axis labels are rendered as text at a fixed angular offset. -
Scale configuration —
scale_y_continuous()sets the radial axis limits and breaks.scale_x_discrete()positions the category labels. Colour scales usescale_fill_manual()andscale_color_manual()withdropcontrolled bykeep_empty_group. -
Circular grid lines — When
polygon = FALSE, dashed circular grid lines are styled viapanel.grid.major.y. -
Dimension calculation —
calculate_plot_dimensions()computes plot height and width fromaspect.ratio, legend metrics, and a base height. -
Faceting —
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis supplied, respecting thekeep_emptysetting for facet variables.
Rarefaction / extrapolation plot
Description
Draws rarefaction and extrapolation curves for biodiversity data using the
iNEXT package. Accepts raw species-abundance / incidence-frequency
lists (which are passed to iNEXT() for estimation) or
pre-computed iNEXT objects.
The function supports three curve types (sample-size-based, sample
completeness, and coverage-based), diversity orders (q), per-group
colouring, faceting, and splitting into separate sub-plots via
split_by. Observed data are marked with points, rarefaction lines
are solid, and extrapolation segments are dashed. Confidence intervals are
shown as semi-transparent ribbons.
Usage
RarefactionPlot(
data,
type = 1,
se = NULL,
group_by = "group",
group_by_sep = "_",
group_name = NULL,
split_by = NULL,
split_by_sep = "_",
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
alpha = 0.2,
pt_size = 3,
line_width = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
type |
An integer specifying the curve type: |
se |
A logical value indicating whether to display confidence intervals
as semi-transparent ribbons around the estimated curve. When |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
A character string used to join multiple
|
group_name |
A character string used as the title for the colour
(and shape) legend. When |
split_by |
A character vector specifying how to split the data into
separate sub-plots. Must be one or both of |
split_by_sep |
A character string used to join multiple
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
pt_size |
A numeric value specifying the size of the observed-data
points. Default: |
line_width |
A numeric value specifying the width of the rarefaction /
extrapolation lines. Default: |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
A numeric seed for reproducibility. Passed to
|
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default |
axes |
A character string specifying how axes should be treated across
the combined layout (passed to |
axis_titles |
A character string specifying how axis titles should be
treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should be
collected across panels (passed to |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments passed to |
Value
A ggplot object (single split), a patchwork object
(multiple splits with combine = TRUE), or a named list of
ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by workflow
When split_by is provided:
-
validate_common_args()checks theseedandfacet_byvalidity. The
typeargument is validated (must be one or more of 1, 2, 3).-
group_by,split_by, andfacet_byare validated for allowed values ("q"and/or"group") and checked for mutual exclusivity — no parameter may overlap with another. If
datais not aniNEXTobject, it is passed toiNEXT()with...(which may containq,datatype,nboot, etc.).The
iNEXTobject is fortifed viafortify()for the requestedtypes. ColumnsAssemblageandOrder.qare renamed togroupandq, respectively.The
separameter is resolved: ifNULLit becomesTRUEwhen the fortifed data containsy.lwr/y.uprcolumns.A
ltycolumn is created (factor with levels"Rarefaction"and"Extrapolation") to distinguish the two line phases via solid / dashed linetypes.-
group_by,split_by, andfacet_byare processed viacheck_columns()withforce_factor = TRUEand multi-column concatenation. If
group_byisNULL, a dummy".group"column is created and the legend is hidden.The data is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
RarefactionPlotAtomic()is called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
set.seed(8525)
spider <- list(
Girdled = c(46, 22, 17, 15, 15, 9, 8, 6, 6, 4, rep(2, 4), rep(1, 12)),
Logged = c(88, 22, 16, 15, 13, 10, 8, 8, 7, 7, 7, 5, 4, 4, 4, 3, 3, 3, 3,
2, 2, 2, 2, rep(1, 14))
)
# Basic sample-size-based rarefaction (type = 1)
RarefactionPlot(spider)
# Multiple diversity orders with faceting
RarefactionPlot(spider, q = c(0, 1, 2), facet_by = "q")
# Multiple diversity orders split into sub-plots
RarefactionPlot(spider, q = c(0, 1, 2), split_by = "q")
# Per-split palettes
RarefactionPlot(spider, q = c(0, 1, 2), split_by = "q",
palette = c("0" = "Paired", "1" = "Set1", "2" = "Dark2"))
# Coverage-based rarefaction (type = 3) with
# group_by = "q" and facet_by = "group"
RarefactionPlot(spider, q = c(0, 1, 2), group_by = "q",
facet_by = "group", palette = "Set1", type = 3)
Atomic rarefaction / extrapolation plot (internal)
Description
Core implementation for drawing a single rarefaction (or extrapolation)
curve from biodiversity data. This is the workhorse behind the exported
RarefactionPlot — it takes a single fortifed data frame
(produced by fortify() on an iNEXT object)
and returns a ggplot object.
The function renders three types of curves:
-
Sample-size-based (
type = 1) — species diversity as a function of sample size (number of individuals or sampling units), with rarefaction (interpolation) and extrapolation segments. -
Sample completeness (
type = 2) — sample coverage as a function of sample size. -
Coverage-based (
type = 3) — species diversity as a function of sample coverage.
Observed data points are marked with geom_point() (shape per group),
the rarefaction / extrapolation lines are drawn with geom_line()
using a solid/dashed linetype to distinguish the two phases, and
confidence intervals are rendered as semi-transparent ribbons when
se = TRUE and the fortifed data contains y.lwr / y.upr
columns.
Usage
RarefactionPlotAtomic(
data,
type = 1,
se = TRUE,
group_by = "group",
group_name = NULL,
pt_size = 3,
line_width = 1,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
alpha = 0.2,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
...
)
Arguments
data |
A data frame produced by |
type |
An integer specifying the curve type: |
se |
A logical value indicating whether to display confidence intervals
as semi-transparent ribbons around the estimated curve. When |
group_by |
A character vector specifying how to group the data for
colouring the lines. Must be one or both of |
group_name |
A character string used as the title for the colour
(and shape) legend. When |
pt_size |
A numeric value specifying the size of the observed-data
points. Default: |
line_width |
A numeric value specifying the width of the rarefaction /
extrapolation lines. Default: |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the colour palette to use.
A named list or vector can be used to specify palettes for different
|
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value between 0 and 1 specifying the transparency
of the confidence-interval ribbon fill. Default: |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
... |
Additional arguments (currently unused in the atomic function; accepted for forward compatibility with the exported wrapper). |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Axis labels — set according to the combination of
typeand the data'sdatatypeattribute ("abundance"vs."incidence"):-
type = 2: x = "Number of individuals" or "Number of sampling units", y = "Sample coverage". -
type = 3 || 4: x = "Sample coverage", y = "Species diversity". -
type = 1(abundance): x = "Number of individuals", y = "Species diversity". -
type = 1(incidence): x = "Number of sampling units", y = "Species diversity".
-
-
Group name fallback — if
group_nameisNULL, it is set to the value ofgroup_by(i.e."q"or"group"). -
Base ggplot — initialises
ggplot(data, aes(x, y, color = group_by)). -
Observed data points —
geom_point()on rows whereMethod == "Observed", with shape mapped to the group variable. -
Colour scale —
scale_color_manual()usingpalette_this(). The legend is suppressed whengroup_byis the dummy".group". -
Shape scale —
scale_shape_discrete()with the same legend-suppression logic. -
Rarefaction / extrapolation lines —
geom_line()with linetype mapped to theltycolumn ("Rarefaction"vs."Extrapolation"). -
Linetype scale —
scale_linetype_manual()withsolidanddashedvalues, legend key width set to 1 cm. -
Theme and labels —
do_call(theme, theme_args),panel.grid.major(grey80 dashed), aspect ratio, legend position / direction, and title / subtitle. -
Confidence ribbon — when
se = TRUE, ageom_ribbon(aes(ymin = y.lwr, ymax = y.upr, fill = group_by))is added with the same per-group palette at transparencyalpha. -
Dimension calculation —
calculate_plot_dimensions()computesheight/widthattributes frombase_height = 4.5,aspect.ratio, and legend metrics. -
Faceting —
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided.
Ridge Plot
Description
Ridge (joy) plot for visualising the distribution of a numeric variable across multiple groups. Each group is rendered as a partially overlapping density curve along the y-axis, making it easy to compare distribution shapes, central tendency, and spread across categories.
The function supports both long and wide data formats:
-
Long form (
in_form = "long", default) — a numeric column (x) plus a factor column (group_by) whose levels become the y-axis ridges. -
Wide form (
in_form = "wide") — multiple numeric columns listed ingroup_byare gathered internally into long form.
Optional vertical reference lines (add_vline) can mark group means,
specific values, or per-group thresholds. Supports faceting, split-by
splitting, and full palette customisation.
Usage
RidgePlot(
data,
x = NULL,
in_form = c("long", "wide"),
split_by = NULL,
split_by_sep = "_",
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
scale = NULL,
keep_na = FALSE,
keep_empty = FALSE,
add_vline = NULL,
vline_type = "solid",
vline_color = TRUE,
vline_width = 0.5,
vline_alpha = 1,
flip = FALSE,
alpha = 0.8,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
x_text_angle = 90,
x_min = NULL,
x_max = NULL,
reverse = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = "none",
legend.direction = "vertical",
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
in_form |
A character string specifying whether |
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string used as the legend title for the
|
scale |
A numeric value controlling the vertical overlap of ridges.
Passed to |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
add_vline |
A specification for vertical reference lines:
|
vline_type |
A character string specifying the line type for the
vertical reference lines. Passed as |
vline_color |
The colour of the vertical reference lines:
|
vline_width |
A numeric value for the thickness of the vertical
reference lines. Passed as |
vline_alpha |
A numeric value in |
flip |
A logical value. If |
alpha |
A numeric value specifying the transparency of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
x_min, x_max |
Numeric limits for the x-axis. When |
reverse |
A logical value. If |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
seed |
The random seed to use. Default is 8525. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments. |
Value
A ggplot object (single plot), a patchwork / wrap_plots object
(when split_by is provided and combine = TRUE), or a list of ggplot
objects (when split_by is provided and combine = FALSE).
split_by Workflow
When split_by is specified, RidgePlot() executes the following pipeline:
-
Argument validation —
validate_common_args()checks the seed and facet-by consistency. -
NA / empty normalisation —
check_keep_na()/check_keep_empty()convertkeep_na/keep_emptyto per-column lists. -
Theme resolution —
process_theme()resolves the theme string to a theme function. -
Split column resolution —
check_columns()validatessplit_by(force_factor, concat_multi). -
Pre-filtering —
process_keep_na_empty()removes NA / empty levels from the split column, thendatais split bysplit_bylevels (order preserved). -
Per-split parameter resolution —
check_palette(),check_palcolor(),check_legend()resolve palette, palcolor, legend.position, and legend.direction for each split. -
Per-split dispatch — each split is passed to
RidgePlotAtomic()with its resolved parameters. Title defaults to the split level name unlesstitleis a function (in which case it is called with the default). -
Combination —
combine_plots()assembles the list of plots viapatchwork::wrap_plots(), applyingnrow,ncol,byrow,axes,axis_titles,guides, anddesign.
Examples
set.seed(8525)
data <- data.frame(
x = c(rnorm(250, -1), rnorm(250, 1)),
group = factor(rep(c("A", NA, LETTERS[3:5]), each = 100), levels = LETTERS[1:6])
)
# basic usage
RidgePlot(data, x = "x") # single ridge (no group_by)
RidgePlot(data, x = "x", add_vline = 0, vline_color = "black")
# grouped ridges
RidgePlot(data, x = "x", group_by = "group")
RidgePlot(data, x = "x", group_by = "group",
keep_na = TRUE, keep_empty = TRUE)
RidgePlot(data, x = "x", group_by = "group", reverse = TRUE)
RidgePlot(data, x = "x", group_by = "group",
add_vline = TRUE, vline_color = TRUE, alpha = 0.7)
# faceting
RidgePlot(data, x = "x", facet_by = "group",
keep_na = TRUE, keep_empty = TRUE)
# wide form
data_wide <- data.frame(
A = rnorm(100),
B = rnorm(100),
C = rnorm(100),
D = rnorm(100),
E = rnorm(100),
group = sample(letters[1:4], 100, replace = TRUE)
)
RidgePlot(data_wide, group_by = LETTERS[1:5], in_form = "wide")
RidgePlot(data_wide, group_by = LETTERS[1:5], in_form = "wide", facet_by = "group")
# split_by with per-split palettes
RidgePlot(data_wide, group_by = LETTERS[1:5], in_form = "wide", split_by = "group",
palette = list(a = "Reds", b = "Blues", c = "Greens", d = "Purples"))
Atomic ridge plot
Description
Core implementation for ridge (joy) plots. Renders overlapping density curves
for each group on the y-axis using ggridges::geom_density_ridges(), with
optional vertical reference lines and wide-to-long data conversion.
The function accepts data in two forms:
-
long form (default) — a numeric
xcolumn plus agroup_byfactor column whose levels become the y-axis ridges. -
wide form — multiple numeric columns named in
group_byare gathered viatidyr::pivot_longer()into.x/.groupcolumns, then processed identically to the long form.
Vertical reference lines (add_vline) can be specified as a numeric vector
(same lines for all groups), a named list (per-group values), or TRUE
(group means). When vline_color = TRUE, each line is coloured with a
darkened blend of the corresponding ridge fill.
Usage
RidgePlotAtomic(
data,
x = NULL,
in_form = c("long", "wide"),
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
add_vline = NULL,
vline_type = "solid",
vline_color = TRUE,
vline_width = 0.5,
vline_alpha = 1,
flip = FALSE,
alpha = 0.8,
scale = NULL,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
x_text_angle = 90,
x_min = NULL,
x_max = NULL,
keep_na = FALSE,
keep_empty = FALSE,
reverse = FALSE,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = "none",
legend.direction = "vertical",
...
)
Arguments
data |
A data frame. Accepted in two forms:
|
x |
A character string specifying the column name for the numeric
values plotted on the x-axis. When |
in_form |
A character string specifying whether |
group_by |
A character string specifying the column(s) whose levels
define the individual ridges on the y-axis. Multiple columns are
concatenated with |
group_by_sep |
A character string used to join multiple |
group_name |
A character string used as the legend title for the
|
add_vline |
A specification for vertical reference lines:
|
vline_type |
A character string specifying the line type for the
vertical reference lines. Passed as |
vline_color |
The colour of the vertical reference lines:
|
vline_width |
A numeric value for the thickness of the vertical
reference lines. Passed as |
vline_alpha |
A numeric value in |
flip |
A logical value. If |
alpha |
A numeric value in |
scale |
A numeric value controlling the vertical overlap of ridges.
Passed to |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
x_text_angle |
A numeric value specifying the angle (in degrees) for
x-axis text when |
x_min, x_max |
Numeric limits for the x-axis. When |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
reverse |
A logical value. If |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
... |
Additional arguments passed to |
Architecture
RidgePlotAtomic executes the following steps:
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplot. -
Wide-to-long conversion — when
in_form = "wide", callstidyr::pivot_longer()on thegroup_bycolumns, producing.group(factor) and.x(values).xandgroup_byare redirected to these synthetic columns. -
Column resolution —
check_columns()validatesx,group_by(force_factor, allow_multi, concat_multi), andfacet_by. -
Default group — when
group_byisNULL, a synthetic.groupfactor with a single space character level is created so the fill pipeline runs uniformly. -
Reverse ordering — if
reverse = TRUE, factor levels ofgroup_byare reversed, flipping the y-axis ridge order. -
NA / empty handling —
process_keep_na_empty()filters data. Whenreverse = TRUEand any group value isNA, the NA level is renamed to the literal string"NA"and moved to the end of the factor so colour mapping and display remain consistent. -
Palette resolution —
palette_this()maps group levels to fill colours. -
Base ggplot — initialises
ggplot(data, aes(x, y, fill))withgroup_byon the y-axis. -
Ridge geometry —
ggridges::geom_density_ridges(alpha, scale). WhenscaleisNULL, ggridges auto-computes the overlap factor. -
Vertical reference lines — if
add_vlineis notNULL/FALSE:-
add_vline = TRUE→ computestapply(x, group_by, mean). -
vline_color = TRUE→ resolves per-group line colours by darkening each fill colour viablend_colors(mode = "multiply"). Named list elements are matched to factor levels. Adds
geom_vline(xintercept, linetype, linewidth, color, alpha).
-
-
Scales and labels —
scale_y_discrete(drop = !keep_empty_group),scale_x_continuous(), andlabs(). -
Fill scale —
scale_fill_manual(). Whenkeep_empty_group = TRUE,drop = FALSE,breaks, andlimitsare set to preserve empty factor levels. -
Flip-aware theme — when
flip = TRUE:-
coord_flip()is applied. x-axis text angle is set from
x_text_anglewith computedhjust/vjustviacalc_just().Major grid lines are drawn on the x-axis.
When
flip = FALSE, y-axis text is right-aligned and grid lines appear on the y-axis.
-
-
Theme application —
do_call(theme, theme_args)applies the resolved theme function, thenaspect.ratioand legend position are set. -
Dimension calculation —
calculate_plot_dimensions(base_height = 1, n_y = nlevels(group_by), y_scale_factor = 1, aspect.ratio, legend, flip)setsheight/widthattributes. The base height of 1 unit per ridge keeps individual ridges compact. -
Faceting —
facet_plot()appliesfacet_grid/facet_wrap, withdrop = !keep_empty_facet.
Ring plot (multi-layer donut chart)
Description
Draws a ring plot (multi-layer donut chart) where each level of x
becomes a concentric ring divided into filled segments by group_by.
The plot is built with geom_col() under coord_polar("y"),
producing a publication-quality ring chart with automatic count aggregation,
per-group colour assignment, faceting, and splitting into sub-plots.
When x = NULL, a single-ring plot is produced (functionally
equivalent to a pie chart via PieChart).
Usage
RingPlot(
data,
x = NULL,
y = NULL,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
label = NULL,
split_by = NULL,
split_by_sep = "_",
facet_by = NULL,
facet_scales = "free_y",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = 1,
keep_na = FALSE,
keep_empty = FALSE,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string used as the fill legend title.
When |
label |
A logical value controlling whether ring labels are shown.
Labels display the |
split_by |
The column(s) to split the data by and produce separate
sub-plots. Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default |
seed |
A numeric seed for reproducibility. Passed to
|
axes |
A character string specifying how axes should be treated across
the combined layout (passed to |
axis_titles |
A character string specifying how axis titles should be
treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should be
collected across panels. Default |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments. |
Value
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by workflow
When split_by is provided:
-
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments for all columns (x,group_by,split_by,facet_by). The
split_bycolumn is validated and its NA / empty levels are processed viaprocess_keep_na_empty(). It is then removed from the per-columnkeep_na/keep_emptylists.The data frame is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
RingPlotAtomic()is called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
See Also
Examples
# Basic single-ring plot (pie-chart-like)
RingPlot(datasets::iris, group_by = "Species")
# Multi-ring plot with faceting
RingPlot(datasets::mtcars, x = "cyl", group_by = "carb", facet_by = "vs")
# Split into sub-plots with per-split palettes
RingPlot(datasets::mtcars, x = "cyl", group_by = "carb", split_by = "vs",
palette = c("0" = "Set1", "1" = "Paired"))
# Custom data with NA and empty levels
data <- data.frame(
x = factor(c("A", "B", NA, "D", "A", "B", NA, "D"), levels = c("A", "B", "C", "D")),
y = c(1, 2, 5, 3, 4, 5, 2, 6),
group = factor(c("a", "a", "a", NA, NA, "c", "c", "c"), levels = c("a", "b", "c"))
)
# Default: NA and empty levels dropped
RingPlot(data, x = "x", y = "y", group_by = "group")
# Keep NA and empty levels
RingPlot(data, x = "x", y = "y", group_by = "group",
keep_na = TRUE, keep_empty = TRUE)
# Per-column keep_na / keep_empty via named lists
RingPlot(data, x = "x", y = "y", group_by = "group",
keep_na = TRUE, keep_empty = list(x = FALSE, group = 'level'))
Atomic ring plot (internal)
Description
Core implementation for drawing a single ring (multi-layer donut) plot.
This is the workhorse behind the exported RingPlot function —
it takes a single data frame (no split_by support) and returns a
ggplot object. Each level of x becomes a concentric ring,
and within each ring the group_by variable divides the ring into
filled segments drawn via geom_col() with coord_polar("y").
When y = NULL, the count of observations per combination is used.
y-values are always normalised to proportions (0–1) within each
(x, facet_by) group so that each complete ring sums to 1.
Usage
RingPlotAtomic(
data,
x = NULL,
y = NULL,
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
label = NULL,
clockwise = TRUE,
keep_na = FALSE,
keep_empty = FALSE,
facet_by = NULL,
facet_scales = "free_y",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column to define the rings
(concentric layers) of the plot. Each unique value becomes one ring.
When |
y |
A character string specifying the numeric column for segment
sizing. When |
group_by |
A character vector of column names to divide each ring
into filled segments. Each unique combination becomes one segment per
ring. Multiple columns are concatenated with |
group_by_sep |
A character string to join multiple |
group_name |
A character string used as the fill legend title.
When |
label |
A logical value controlling whether ring labels are shown.
Labels display the |
clockwise |
A logical value. When |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
Column resolution —
x,group_by,y, andfacet_byare validated and transformed viacheck_columns. IfxisNULL, a dummy.xcolumn (value1) is created, producing a single-ring (pie-chart-like) plot. Ifgroup_byisNULL, a dummy.group_byfactor is created and the legend is suppressed. Multi-columngroup_byinputs are concatenated withgroup_by_sep. -
NA / empty-level handling —
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. Per-columnkeep_emptysettings are extracted forx,group_by, andfacet_byindependently. The facet columns must have identicalkeep_emptyvalues. -
Count aggregation — when
y = NULL, the count of observations in each unique (x,group_by,facet_by) combination is computed as a new.ycolumn. Factor levels are preserved after aggregation. -
Proportion scaling — y-values are divided by the sum within each (
x,facet_by) group, normalising each ring to sum to 1.0. This is essential for polar coordinates where each ring represents a full 360 degrees. -
Ring resolution — The levels of
xare reversed so the outermost ring appears first in the data (rings are drawn outward from the origin).NAlevels are appended. -
Label logic — When
label = NULL, labels are automatically suppressed for single-ring plots and shown for multi-ring plots. Labels are placed at the inner edge of each ring viageom_label(). -
Clockwise ordering — When
clockwise = TRUE(default), thegroup_bylevels are reversed so segments appear clockwise from the top. The legend guide also reverses its order. -
Colour mapping —
palette_this()assigns colours to allgroup_bylevels, includingNA(defaulting to"grey80"). -
Plot assembly — The
ggplotobject is built withgeom_col()(ring segments),coord_polar("y")(polar transform),scale_x_discrete()(with a leading space level as the donut hole), andscale_fill_manual()with per-group colours. All axes, ticks, grid lines, and panel borders are removed for a clean appearance. The fill scaledropargument is controlled bykeep_empty_group. -
Dimension calculation —
calculate_plot_dimensions()computes plot height and width fromaspect.ratioand legend metrics. The resultingheight/widthattributes are stored on theggplotobject. -
Faceting —
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided, respecting thekeep_emptysetting for facet variables.
Sankey / Alluvial Plot
Description
Draws Sankey (alluvial) diagrams to visualise flow, movement, or change from one categorical state to another across discrete positions (time points, stages, or groups). The plot consists of nodes (vertical blocks, or strata) representing categories at each position, and links (alluvia / flows) representing the observation units that move between categories across positions.
The function accepts data in several formats, controlled by in_form:
"lodes"/"long"Each row is an observation at one x-position, with columns for
x,stratum,alluvium, and optionallyy."alluvia"/"wide"Each row is an observation unit tracked across all positions;
xcolumns represent the categories at each position. Converted internally viato_lodes_form()."counts"Numeric columns under each
xrepresent frequencies. When the first element ofxis".", thelinks_fill_byvalues are injected as an additional first column of nodes, visualising the source distribution of flows."auto"(default)Automatically detects the format: numeric multi-column
x→"counts"; multi-columnxpassingis_alluvia_form→"alluvia"; otherwise →"lodes".
Supports split_by to produce separate sub-plots for different subsets of the data, facet_by for within-plot faceting, and independent styling of nodes and links (colours, alpha, borders, labels, and legend behaviour).
AlluvialPlot is an alias of SankeyPlot.
Usage
SankeyPlot(
data,
in_form = c("auto", "long", "lodes", "wide", "alluvia", "counts"),
x,
x_sep = "_",
y = NULL,
stratum = NULL,
stratum_sep = "_",
alluvium = NULL,
alluvium_sep = "_",
split_by = NULL,
split_by_sep = "_",
keep_empty = TRUE,
flow = FALSE,
expand = c(0, 0, 0, 0),
nodes_legend = c("auto", "separate", "merge", "none"),
nodes_color = "grey30",
links_fill_by = NULL,
links_fill_by_sep = "_",
links_name = NULL,
links_color = "gray80",
nodes_palette = "Paired",
nodes_palcolor = NULL,
nodes_alpha = 1,
nodes_label = FALSE,
nodes_label_miny = 0,
nodes_width = 0.25,
links_palette = "Paired",
links_palcolor = NULL,
palreverse = FALSE,
links_alpha = 0.6,
legend.box = "vertical",
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
flip = FALSE,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
AlluvialPlot(
data,
in_form = c("auto", "long", "lodes", "wide", "alluvia", "counts"),
x,
x_sep = "_",
y = NULL,
stratum = NULL,
stratum_sep = "_",
alluvium = NULL,
alluvium_sep = "_",
split_by = NULL,
split_by_sep = "_",
keep_empty = TRUE,
flow = FALSE,
expand = c(0, 0, 0, 0),
nodes_legend = c("auto", "separate", "merge", "none"),
nodes_color = "grey30",
links_fill_by = NULL,
links_fill_by_sep = "_",
links_name = NULL,
links_color = "gray80",
nodes_palette = "Paired",
nodes_palcolor = NULL,
nodes_alpha = 1,
nodes_label = FALSE,
nodes_label_miny = 0,
nodes_width = 0.25,
links_palette = "Paired",
links_palcolor = NULL,
palreverse = FALSE,
links_alpha = 0.6,
legend.box = "vertical",
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
flip = FALSE,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
in_form |
A character string specifying the input data format.
One of |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
x_sep |
A character string to join multiple |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
stratum |
A character string specifying the column that defines the
node categories at each x-axis position. Each unique value becomes a
stratum (node block) at each x position. When |
stratum_sep |
A character string to join multiple |
alluvium |
A character string specifying the column that identifies
individual flows (alluvia) across x-axis positions. Each unique value
represents a single observational unit tracked across positions. When
|
alluvium_sep |
A character string to join multiple |
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
flow |
A logical value. When |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
nodes_legend |
Controls how the node legend is displayed. One of:
|
nodes_color |
A character string specifying the border colour of the
node (stratum) rectangles. Use the special value |
links_fill_by |
A character string specifying the column that
determines the fill colour of the links (alluvia / flows). When
|
links_fill_by_sep |
A character string to join multiple
|
links_name |
A character string for the legend title of the link fill
scale. When |
links_color |
A character string specifying the border colour of the
links (alluvia / flows). Use the special value |
nodes_palette |
A character string specifying the colour palette for
the node (stratum) fill. Passed to |
nodes_palcolor |
A character vector of custom colours for the node
fill, used as |
nodes_alpha |
A numeric value in |
nodes_label |
A logical value. When |
nodes_label_miny |
A numeric value specifying the minimum y
(frequency) threshold for displaying node labels. Nodes with y-values
below this threshold are not labelled. Default |
nodes_width |
A numeric value (typically 0–1) specifying the width of
the node (stratum) rectangles as a fraction of the x-axis spacing.
Default |
links_palette |
A character string specifying the colour palette for
the link fill. Passed to |
links_palcolor |
A character vector of custom colours for the link
fill, used as |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
links_alpha |
A numeric value in |
legend.box |
A character string specifying the arrangement of legend
boxes, either |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
flip |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
seed |
The random seed to use. Default is 8525. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments. |
Value
A ggplot object (single panel, no split_by), a
patchwork object (when combine = TRUE and
split_by is used), or a named list of ggplot objects
(when combine = FALSE). Each plot carries height and
width attributes in inches.
split_by workflow
When split_by is provided:
The
split_bycolumn(s) are validated and coerced to factors viacheck_columns(). Multi-columnsplit_byis concatenated withsplit_by_sep.Empty factor levels are dropped from
split_by.The data is split by
split_bylevel (preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".-
SankeyPlotAtomic()is called for each split, withtitleresolved per level (supports function-valued titles). Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
# Examples from ggalluvial datasets
set.seed(8525)
data(UCBAdmissions, package = "datasets")
UCBAdmissions <- as.data.frame(UCBAdmissions)
SankeyPlot(as.data.frame(UCBAdmissions), x = c("Gender", "Dept"),
y = "Freq", nodes_width = 1/12, links_fill_by = "Admit", nodes_label = TRUE,
nodes_palette = "simspec", links_palette = "Set1", links_alpha = 0.5,
nodes_palcolor = "black", links_color = "transparent")
data(HairEyeColor, package = "datasets")
SankeyPlot(as.data.frame(HairEyeColor), x = c("Hair", "Eye", "Sex"),
y = "Freq", links_fill_by = "Eye", nodes_width = 1/8, nodes_alpha = 0.4,
flip = TRUE, reverse = FALSE, knot.pos = 0, links_color = "transparent",
ylab = "Freq", links_alpha = 0.5, links_name = "Eye (links)", links_palcolor = c(
Brown = "#70493D", Hazel = "#E2AC76", Green = "#3F752B", Blue = "#81B0E4"))
data(Refugees, package = "alluvial")
country_regions <- c(
Afghanistan = "Middle East",
Burundi = "Central Africa",
`Congo DRC` = "Central Africa",
Iraq = "Middle East",
Myanmar = "Southeast Asia",
Palestine = "Middle East",
Somalia = "Horn of Africa",
Sudan = "Central Africa",
Syria = "Middle East",
Vietnam = "Southeast Asia"
)
Refugees$region <- country_regions[Refugees$country]
SankeyPlot(Refugees, x = "year", y = "refugees", alluvium = "country",
links_fill_by = "country", links_color = ".fill", links_alpha = 0.75,
links_palette = "Set3", facet_by = "region", x_text_angle = -45, nodes_legend = "none",
theme_args = list(strip.background = ggplot2::element_rect(fill="grey80")),
decreasing = FALSE, nodes_width = 0, nodes_color = "transparent", ylab = "refugees",
title = "Refugee volume by country and region of origin")
data(majors, package = "ggalluvial")
majors$curriculum <- as.factor(majors$curriculum)
SankeyPlot(majors, x = "semester", stratum = "curriculum", alluvium = "student",
links_fill_by = "curriculum", flow = TRUE, stat = "alluvium", nodes_palette = "Set2",
links_palette = "Set2")
data(vaccinations, package = "ggalluvial")
vaccinations <- transform(vaccinations,
response = factor(response, rev(levels(response))))
SankeyPlot(vaccinations, x = "survey", stratum = "response", alluvium = "subject",
y = "freq", links_fill_by = "response", nodes_label = TRUE, nodes_alpha = 0.5,
nodes_palette = "seurat", links_palette = "seurat", links_alpha = 0.5,
legend.position = "none", flow = TRUE, expand = c(0, 0, 0, .15), stat = "alluvium",
title = "vaccination survey responses at three points in time")
data(Titanic, package = "datasets")
SankeyPlot(as.data.frame(Titanic), x = c("Class", "Sex"), y = "Freq",
links_fill_by = "Survived", flow = TRUE, facet_by = "Age", facet_scales = "free_y",
nodes_label = TRUE, expand = c(0.05, 0), xlab = "", links_palette = "Set1",
nodes_palcolor = "white", nodes_label_miny = 10)
# Simulated examples
df <- data.frame(
Clone = paste0("clone", 1:10),
Timepoint1 = sample(c(rep(0, 30), 1:100), 10),
Timepoint2 = sample(c(rep(0, 30), 1:100), 10)
)
SankeyPlot(df, x = c("Timepoint1", "Timepoint2"), alluvium = "Clone",
links_color = ".fill")
df <- data.frame(
Clone = rep(paste0("clone", 1:6), each = 2),
Timepoint1 = sample(c(rep(0, 30), 1:100), 6),
Timepoint2 = sample(c(rep(0, 30), 1:100), 6),
Group = rep(c("A", "B"), 6)
)
SankeyPlot(df, x = c(".", "Timepoint1", "Timepoint2"),
stratum = "Group", links_fill_by = "Clone", links_color = ".fill")
Atomic Sankey / alluvial diagram (internal)
Description
Core implementation for drawing a Sankey (alluvial) diagram using
geom_alluvium (or geom_flow)
and geom_stratum. This function takes a single
data frame (no split_by support) and returns a ggplot object
with faceting applied.
The function supports five input formats (in_form) which control how
the data columns are interpreted. Nodes (strata) are rendered as vertical
blocks whose fill colour and alpha can be customised independently of the
links (alluvia / flows) connecting them. Link colours can match node
colours or use a separate palette; link borders can be set to a fixed colour
or to follow the fill colour (links_color = ".fill").
Automatic legend resolution determines whether nodes on different x-axis positions receive a merged legend or separate legends, based on overlaps between stratum values across positions.
Usage
SankeyPlotAtomic(
data,
in_form = c("auto", "long", "lodes", "wide", "alluvia", "counts"),
x,
x_sep = "_",
y = NULL,
stratum = NULL,
stratum_sep = "_",
alluvium = NULL,
alluvium_sep = "_",
flow = FALSE,
nodes_color = "grey30",
links_fill_by = NULL,
links_fill_by_sep = "_",
links_name = NULL,
links_color = "gray80",
nodes_palette = "Paired",
nodes_palcolor = NULL,
palreverse = FALSE,
nodes_alpha = 1,
nodes_label = FALSE,
nodes_width = 0.25,
nodes_label_miny = 0,
nodes_legend = c("auto", "separate", "merge", "none"),
expand = c(0, 0, 0, 0),
links_palette = "Paired",
links_palcolor = NULL,
links_alpha = 0.6,
legend.box = "vertical",
keep_empty = TRUE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
flip = FALSE,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
...
)
Arguments
data |
A data frame. |
in_form |
A character string specifying the input data format.
One of |
x |
A character vector of column name(s) for the x-axis categories.
Each unique value or concatenated pair represents a time point, state, or
position along the horizontal axis. Behaviour depends on |
x_sep |
A character string to join multiple |
y |
A character string specifying the numeric column for the y-axis
(frequency / value). When |
stratum |
A character string specifying the column that defines the
node categories at each x-axis position. Each unique value becomes a
stratum (node block) at each x position. When |
stratum_sep |
A character string to join multiple |
alluvium |
A character string specifying the column that identifies
individual flows (alluvia) across x-axis positions. Each unique value
represents a single observational unit tracked across positions. When
|
alluvium_sep |
A character string to join multiple |
flow |
A logical value. When |
nodes_color |
A character string specifying the border colour of the
node (stratum) rectangles. Use the special value |
links_fill_by |
A character string specifying the column that
determines the fill colour of the links (alluvia / flows). When
|
links_fill_by_sep |
A character string to join multiple
|
links_name |
A character string for the legend title of the link fill
scale. When |
links_color |
A character string specifying the border colour of the
links (alluvia / flows). Use the special value |
nodes_palette |
A character string specifying the colour palette for
the node (stratum) fill. Passed to |
nodes_palcolor |
A character vector of custom colours for the node
fill, used as |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
nodes_alpha |
A numeric value in |
nodes_label |
A logical value. When |
nodes_width |
A numeric value (typically 0–1) specifying the width of
the node (stratum) rectangles as a fraction of the x-axis spacing.
Default |
nodes_label_miny |
A numeric value specifying the minimum y
(frequency) threshold for displaying node labels. Nodes with y-values
below this threshold are not labelled. Default |
nodes_legend |
Controls how the node legend is displayed. One of:
|
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
links_palette |
A character string specifying the colour palette for
the link fill. Passed to |
links_palcolor |
A character vector of custom colours for the link
fill, used as |
links_alpha |
A numeric value in |
legend.box |
A character string specifying the arrangement of legend
boxes, either |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
flip |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
... |
Additional arguments passed to
|
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
Format resolution —
in_formis matched and aliased ("long"→"lodes","wide"→"alluvia"). -
Data parsing by format — one of five code paths executes:
-
Lodes / long —
x,stratum,alluvium, andlinks_fill_byare validated viacheck_columns(). Multi-column inputs are concatenated with their respective separators. WhenyisNULL, counts are computed per (x,stratum,alluvium,links_fill_by,facet_by). -
Counts (x without
"."prefix) — numericxcolumns are pivoted to long form viapivot_longer(), creating the y-axis from the cell values.alluviumandstratumdefault tolinks_fill_by. -
Counts with source node (x with
"."as first element,is_flowcounts) — same as counts but also injectslinks_fill_byvalues as an additional first column of nodes, visualising how flows originate from source groups. -
Alluvia / wide — validated via
is_alluvia_form()and converted to lodes form viato_lodes_form().stratumandalluviumare ignored. -
Auto / fallback — when no other branch matches, the lodes path is attempted and validated via
is_lodes_form().
-
-
Palette assignment —
palette_this()resolves colours for both nodes (nodes_palette/nodes_palcolor) and links (links_palette/links_palcolor). -
Flow-counts guide logic — when
is_flowcountsisTRUE, the links guide is suppressed if the first-column node colours match the link colours, avoiding redundant legends. When the palettes are identical but colours differ (too few colours in the palette), the first-column node colours are reused. -
Legend auto-detection — when
nodes_legend = "auto": ifnodes_label = TRUEor ifstratumandlinks_fill_byshare identical values and colours, the nodes legend is hidden. Otherwise, overlapping stratum values across x-axis positions are checked: any overlap triggers a merged legend; no overlap produces separate legends per position. -
Base ggplot — constructed with
aes(x = x, stratum = stratum, alluvium = alluvium, y = y). -
Separate node fill layers — when
stratumdiffers fromlinks_fill_byandnodes_legend = "separate", ageom_col()+scale_fill_manual()layer pair is added per x-axis position, each followed bynew_scale_fill()to produce independent legends. -
Link rendering —
geom_alluvium()(default) orgeom_flow()whenflow = TRUE. Whenlinks_color = ".fill", the colour aesthetic is mapped tolinks_fill_byand the colour scale guide is suppressed. Forgeom_flowwith a distinctstratumandlinks_fill_by,stat = "alluvium"is forced to preserve the fill variable through the flow stat transformation. -
Link fill scale —
scale_fill_manual()withlinks_colorsand the resolvedlinks_guide. -
Node rendering —
geom_stratum()withnodes_color(border) andnodes_alpha. Whennodes_color = ".fill", the colour aesthetic maps tostratum. -
Node fill scale —
scale_fill_manual()withnodes_colors. The guide is"none"whennodes_legendis"none"or"separate"(already handled by per-position layers); otherwise"legend". -
Labels — when
nodes_label = TRUE,geom_label()withstat = StatStratumandmin.y = nodes_label_miny. -
Axes, theme, labels —
scale_x_discrete(),scale_y_continuous(), custom theme, plot title / subtitle, axis labels, and aesthetic adjustments (aspect ratio, legend position / direction, grid removal, x-text angle). -
Coordinate flip — when
flip = TRUE,coord_flip()swaps the axes. -
Dimension calculation —
calculate_plot_dimensions()computesheightandwidthattributes from the number of x-axis positions, legend metrics, and flip state, scaled byaspect.ratio. -
Faceting —
facet_plot()wraps the result whenfacet_byis provided.
Scatter Plot
Description
Draws a scatter plot with optional size encoding, colour encoding
(continuous gradient or discrete palette), point highlighting, and axis
transformations. This is the user-facing wrapper around
ScatterPlotAtomic that adds split_by support
(generating separate sub-plots per group) and combines them via
patchwork.
Key features:
-
Variable point size –
size_byaccepts either a numeric constant or a column name. -
Colour modes – numeric
color_byproduces a continuous gradient; factor/charactercolor_byproduces a discrete palette. -
Colour scale trimming –
lower_quantile/upper_quantile(or explicitlower_cutoff/upper_cutoff) trim/clamp continuous colour scale extremes. -
Border modes –
border_colorcan be a constant colour,TRUE(track the fill gradient), or omitted. -
Point highlighting –
highlightaccepts indices, rownames, logicalTRUE, or a string expression. -
Axis transformation –
xtrans/ytranssupport log, sqrt, and other scale transformations. -
Split sub-plots –
split_byproduces one scatter plot per group level, combined into a singlepatchworklayout.
Usage
ScatterPlot(
data,
x,
y,
size_by = 2,
size_name = NULL,
color_by = NULL,
color_name = NULL,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
palreverse = FALSE,
split_by = NULL,
split_by_sep = "_",
shape = 21,
alpha = ifelse(shape %in% 21:25, 0.65, 1),
border_color = "black",
highlight = NULL,
highlight_shape = 16,
highlight_size = 3,
highlight_color = "red",
highlight_alpha = 1,
theme = "theme_this",
theme_args = list(),
palette = ifelse(!is.null(color_by) && !is.numeric(data[[color_by]]), "Paired",
"Spectral"),
palcolor = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
size_by |
Either a numeric constant (uniform dot size) or a character
string naming a numeric column whose values control dot size via
|
size_name |
A character string for the size legend title. When
|
color_by |
A character string naming a column whose values control
dot colour. Can be numeric (continuous gradient via
|
color_name |
A character string for the colour legend title. When
|
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
split_by |
The column(s) to split data by and generate separate scatter
plots for each level. The split column is processed before splitting;
multiple columns are concatenated with |
split_by_sep |
A character string used to concatenate multiple
|
shape |
A numeric value specifying the point shape. Default: |
alpha |
A numeric value specifying the transparency of the plot. |
border_color |
Controls the point border colour. For shapes 21–25:
For shapes without a fill aesthetic (not 21–25), this parameter has no effect. |
highlight |
Specifies which points to highlight with an overlaid
|
highlight_shape |
A numeric value specifying the point shape for
highlighted points. Default: |
highlight_size |
A numeric value specifying the size of highlighted
points. Default: |
highlight_color |
A character string specifying the colour of
highlighted points. Default: |
highlight_alpha |
A numeric value in |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
combine |
A logical value. If |
nrow, ncol, byrow |
Integers controlling the layout of combined plots via
|
seed |
The random seed for reproducibility. Passed to
|
axes, axis_titles |
Strings controlling how axes and axis titles are
handled across combined plots. Passed to |
guides |
A string controlling guide collection across combined plots.
Passed to |
design |
A custom layout specification for combined plots. Passed to
|
... |
Additional arguments. |
Value
A ggplot object (single plot), a patchwork object
(when combine = TRUE with split_by), or a named list of
ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by Workflow
When split_by is provided:
-
Seed validation –
validate_common_args()sets the random seed for reproducibility. -
Theme resolution –
process_theme()resolves thethemestring or function. -
Split column resolution –
check_columns()validatessplit_by(force_factor, allow_multi, concat_multi). -
Data splitting – unused factor levels are dropped and the data is split into a named list (preserving factor level order). When
split_by = NULL, a single-element list named"..."is used. -
Per-split palette / colour –
check_palette()andcheck_palcolor()resolve per-split palette and colour overrides. -
Per-split legend –
check_legend()resolveslegend.positionandlegend.directionper split. -
Per-split title – when
titleis a function, it receives the default title (the split level name) and can return a custom string; otherwisetitle %||% split_levelis used. -
Dispatch – each split subset is passed to
ScatterPlotAtomic(). -
Combination –
combine_plots()assembles the list of plots viapatchwork::wrap_plots, honouringnrow/ncol/byrow/design.
Examples
set.seed(8525)
data <- data.frame(
x = rnorm(20),
y = rnorm(20),
w = abs(rnorm(20)),
t = sample(c("A", "B"), 20, replace = TRUE)
)
# --- Basic scatter plot ---
ScatterPlot(data, x = "x", y = "y")
# --- Highlight points ---
ScatterPlot(data, x = "x", y = "y", highlight = 'x > 0')
# --- Size encoding (column name) ---
ScatterPlot(data, x = "x", y = "y", size_by = "w")
# --- Colour encoding (numeric gradient) ---
ScatterPlot(data, x = "x", y = "y", color_by = "w")
# --- Colour encoding (categorical) with border ---
ScatterPlot(data, x = "x", y = "y", size_by = "w", color_by = "t",
border_color = "red")
# --- Border colour tracks fill gradient ---
ScatterPlot(data, x = "x", y = "y", size_by = "w", color_by = "t",
border_color = TRUE)
# --- Shape without fill (single colour aesthetic) ---
ScatterPlot(data, x = "x", y = "y", size_by = "w", color_by = "t",
shape = 1, palette = "Set1")
# --- split_by with per-split palcolor ---
ScatterPlot(data, x = "x", y = "y", split_by = "t",
palcolor = list(A = "blue", B = "red"))
# --- Colour scale limits (quantile-based) ---
ScatterPlot(data, x = "x", y = "y", color_by = "w",
lower_quantile = 0.1, upper_quantile = 0.9)
# --- Colour scale limits (explicit cutoffs) ---
ScatterPlot(data, x = "x", y = "y", color_by = "w",
lower_cutoff = 0, upper_cutoff = 1)
Atomic scatter plot (internal)
Description
Core implementation for drawing a single scatter plot. This is the workhorse
behind the exported ScatterPlot function – it takes a
single data frame (no split_by support) and returns a
ggplot object. The plot positions points by x and y
coordinates (both numeric), with optional size encoding via a third numeric
variable (size_by), and colour encoding (color_by) that can be
numeric (continuous gradient) or categorical (discrete palette).
Key features:
-
Variable point size –
size_byaccepts either a numeric constant (uniform dot size) or a column name (size scales with value viascale_size_area()). -
Colour modes –
color_bycan be numeric (rendered as a continuous gradient viascale_fill_gradientn()orscale_color_gradientn()) or factor/character (discrete palette viascale_fill_manual()/scale_color_manual()). -
Shape support – shapes 21–25 support separate fill and border (
color) aesthetics; all other shapes use only the colour aesthetic. Theborder_colorparameter can be a constant colour,TRUE(track the fill gradient), or omitted. -
Colour scale trimming –
lower_quantile/upper_quantile(or explicitlower_cutoff/upper_cutoff) trim/clamp the continuous colour scale extremes. -
Axis transformation –
xtransandytransapply arbitrary scale transformations (e.g."log10","sqrt") to the x and y axes viascale_x_continuous()/scale_y_continuous(). -
Point highlighting –
highlightaccepts indices, rownames, logicalTRUE, or a string expression to select points that are overlaid with a distinct shape, size, colour, and alpha.
Usage
ScatterPlotAtomic(
data,
x,
y,
size_by = 2,
size_name = NULL,
color_by = NULL,
color_name = NULL,
palreverse = FALSE,
theme = "theme_this",
theme_args = list(),
alpha = ifelse(shape %in% 21:25, 0.65, 1),
shape = 21,
border_color = "black",
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
xtrans = "identity",
ytrans = "identity",
highlight = NULL,
highlight_shape = 16,
highlight_size = 3,
highlight_color = "red",
highlight_alpha = 1,
palette = ifelse(!is.null(color_by) && !is.numeric(data[[color_by]]), "Paired",
"Spectral"),
palcolor = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the numeric column to use for the x-axis. A numeric column is expected. |
y |
A character string specifying the numeric column to use for the y-axis. A numeric column is expected. |
size_by |
Either a numeric constant (uniform dot size) or a character
string naming a numeric column whose values control dot size via
|
size_name |
A character string for the size legend title. When
|
color_by |
A character string naming a column whose values control
dot colour. Can be numeric (continuous gradient via
|
color_name |
A character string for the colour legend title. When
|
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
alpha |
A numeric value specifying the transparency of the plot. |
shape |
A numeric value specifying the point shape. Default: |
border_color |
Controls the point border colour. For shapes 21–25:
For shapes without a fill aesthetic (not 21–25), this parameter has no effect. |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
xtrans |
A character string specifying the transformation for the
x-axis, passed to |
ytrans |
A character string specifying the transformation for the
y-axis, passed to |
highlight |
Specifies which points to highlight with an overlaid
|
highlight_shape |
A numeric value specifying the point shape for
highlighted points. Default: |
highlight_size |
A numeric value specifying the size of highlighted
points. Default: |
highlight_color |
A character string specifying the colour of
highlighted points. Default: |
highlight_alpha |
A numeric value in |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch – selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Column resolution –
facet_byis validated and forced to factor viacheck_columns().size_byis validated when it is a column name; numeric constants are kept as-is.color_byis validated. -
Dummy colour guard – when
color_by = NULL, a synthetic.color_bycolumn (constant"") is created and the colour legend is suppressed. -
Categorical colour coercion – when
color_byis a non-numeric column, it is forced to factor viacheck_columns()withforce_factor = TRUE. -
Continuous colour scale preparation – when
color_byis numeric,prepare_continuous_color_scale()computes quantile-trimmed or cutoff-clamped colour range endpoints (feat_colors_value) and winsorizes out-of-range data. -
Highlight resolution –
highlightis processed into a subset data frame (hidata) via one of four paths:TRUE(all points), numeric index vector, a single string expression (parsed withrlang::parse_expr()and applied viafilter()), or a character vector of rownames. An error is thrown if rownames are used on data without row names. -
Shape fill detection – determines whether the point shape (
shape) supports a separate fill aesthetic (shapes 21–25). -
Base ggplot – initialises
ggplot(data, aes(x, y)). -
Point layer configuration – the aesthetic mapping and constant aesthetics for
geom_point()are assembled:-
Fill vs colour: shapes 21–25 map
fill(and optionallycolorwhenborder_color = TRUE); other shapes mapcolor. -
Size: a numeric
size_byis passed as a constant aesthetic; a column name is mapped to thesizeaesthetic.
-
-
Size scale – when
size_byis a column name,scale_size_area(max_size = 6)is added with a size legend (order = 1, title =size_name %||% size_by). -
Fill / colour scale (4 branches):
-
Shape with fill + numeric colour:
scale_fill_gradientn()withfeat_colors_valuerescaling and either a colour-bar legend or suppressed guide. Whenborder_color = TRUE, a matchingscale_color_gradientn()is added. -
Shape with fill + factor colour:
scale_fill_manual()withpalette_this()colours and a discrete legend. Whenborder_color = TRUE, a matchingscale_color_manual()is added. -
Shape without fill + numeric colour:
scale_color_gradientn()with continuous colour-bar legend. -
Shape without fill + factor colour:
scale_color_manual()with discrete legend.
-
-
Highlight overlay – when
hidatais non-NULL, a secondgeom_point()layer is added usinghighlight_shape,highlight_color,highlight_size, andhighlight_alpha. The fill or colour aesthetic is chosen based on whetherhighlight_shapeis 21–25. -
Axis scales –
scale_x_continuous(trans = xtrans)andscale_y_continuous(trans = ytrans)apply the requested transformations. -
Labels and theme –
labs(title, subtitle, x, y)sets plot annotations.do_call(theme, theme_args)applies the theme.panel.grid.majoris set to grey80 dashed lines. -
Dimension calculation –
calculate_plot_dimensions()computes plotheightandwidthfrombase_height = 5,aspect.ratio, and legend metrics (number of legend items and maximum label character width). -
Faceting –
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided.
Spatial visualization functions for terra objects and point data
Description
These functions provide publication-quality spatial visualizations built on ggplot2, supporting raster images, categorical masks, vector shapes, and point data from the terra package or standard data frames.
Usage
SpatImagePlot(
data,
ext = NULL,
raster = NULL,
raster_dpi = NULL,
flip_y = TRUE,
palette = "turbo",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
fill_name = NULL,
return_layer = FALSE,
theme = "theme_box",
theme_args = list(),
legend.position = ifelse(return_layer, "none", "right"),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525
)
SpatMasksPlot(
data,
ext = NULL,
flip_y = TRUE,
add_border = TRUE,
border_color = "black",
border_size = 0.5,
border_alpha = 1,
palette = "turbo",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
fill_name = NULL,
return_layer = FALSE,
theme = "theme_box",
theme_args = list(),
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525
)
SpatShapesPlot(
data,
x = NULL,
y = NULL,
group = NULL,
ext = NULL,
flip_y = TRUE,
fill_by = NULL,
border_color = "black",
border_size = 0.5,
border_alpha = 1,
palette = NULL,
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
fill_name = NULL,
highlight = NULL,
highlight_alpha = 1,
highlight_size = 1,
highlight_color = "black",
highlight_stroke = 0.8,
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
return_layer = FALSE,
theme = "theme_box",
theme_args = list(),
legend.position = ifelse(return_layer, "none", "right"),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525
)
## S3 method for class 'SpatVector'
SpatShapesPlot(
data,
x = NULL,
y = NULL,
group = NULL,
ext = NULL,
flip_y = TRUE,
fill_by = NULL,
border_color = "black",
border_size = 0.5,
border_alpha = 1,
palette = NULL,
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
fill_name = NULL,
highlight = NULL,
highlight_alpha = 1,
highlight_size = 1,
highlight_color = "black",
highlight_stroke = 0.8,
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
return_layer = FALSE,
theme = "theme_box",
theme_args = list(),
legend.position = ifelse(return_layer, "none", "right"),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525
)
## S3 method for class 'data.frame'
SpatShapesPlot(
data,
x,
y,
group,
ext = NULL,
flip_y = TRUE,
fill_by = "grey90",
border_color = "black",
border_size = 0.5,
border_alpha = 1,
palette = NULL,
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
fill_name = NULL,
highlight = NULL,
highlight_alpha = 1,
highlight_size = 1,
highlight_color = "black",
highlight_stroke = 0.8,
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
return_layer = FALSE,
theme = "theme_box",
theme_args = list(),
legend.position = ifelse(return_layer, "none", "right"),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525
)
SpatPointsPlot(
data,
x = NULL,
y = NULL,
ext = NULL,
flip_y = TRUE,
color_by = NULL,
size_by = NULL,
size = NULL,
fill_by = NULL,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
palette = NULL,
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
color_name = NULL,
size_name = NULL,
shape = 16,
border_color = "black",
border_size = 0.5,
border_alpha = 1,
raster = NULL,
raster_dpi = c(512, 512),
hex = FALSE,
hex_linewidth = 0.5,
hex_count = FALSE,
hex_bins = 50,
hex_binwidth = NULL,
label = FALSE,
label_size = 4,
label_fg = "white",
label_bg = "black",
label_bg_r = 0.1,
label_repel = FALSE,
label_repulsion = 20,
label_pt_size = 1,
label_pt_color = "black",
label_segment_color = "black",
label_insitu = FALSE,
label_pos = c("median", "mean", "max", "min", "first", "last", "center", "random"),
highlight = NULL,
highlight_alpha = 1,
highlight_size = 1,
highlight_color = "black",
highlight_stroke = 0.8,
graph = NULL,
graph_x = NULL,
graph_y = NULL,
graph_xend = NULL,
graph_yend = NULL,
graph_value = NULL,
edge_size = c(0.05, 0.5),
edge_alpha = 0.1,
edge_color = "grey40",
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
return_layer = FALSE,
theme = "theme_box",
theme_args = list(),
legend.position = ifelse(return_layer, "none", "right"),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
seed = 8525
)
Arguments
data |
A |
ext |
A numeric vector of length 4 |
raster |
Whether to rasterize for efficient rendering of large
datasets. Default is |
raster_dpi |
A numeric vector of length 1 or 2 specifying the
raster output resolution in pixels. Default is |
flip_y |
Whether to negate the y-coordinates so the axis labels can
be displayed with reversed sign. Default is |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
fill_name |
A character string for the fill legend title. |
return_layer |
Whether to return a list of ggplot layers instead
of a complete plot. Default is |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
seed |
The random seed to use. Default is 8525. |
add_border |
Whether to add polygon borders around mask regions in
|
border_color |
A character string for the border color. Default is
|
border_size |
A numeric value for the border line width.
Default is |
border_alpha |
A numeric value for the border transparency.
Default is |
x |
A character string specifying the x coordinate column for
|
y |
A character string specifying the y coordinate column for
|
group |
A character string specifying the grouping column for
|
fill_by |
A character string or vector specifying the column(s) to
map to fill color in |
highlight |
A character vector of row names to highlight, a filter
expression string (e.g., |
highlight_alpha |
A numeric value for highlight transparency.
Default is |
highlight_size |
A numeric value for the highlight marker size.
Default is |
highlight_color |
A character string for the highlight marker
color. Default is |
highlight_stroke |
A numeric value for the highlight stroke width
(added to |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
color_by |
A character string or vector specifying the column(s) to
map to point color in |
size_by |
A character string specifying the column to map to point
size in |
size |
A numeric value for a fixed point size in
|
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
color_name |
A character string for the color legend title. |
size_name |
A character string for the size legend title. |
shape |
A numeric value (21–25 for border shapes) or character
string specifying the point shape in |
hex |
Whether to use hexagonal binning in |
hex_linewidth |
A numeric value for the hex bin border width.
Default is |
hex_count |
Whether to show hex bin count as point opacity.
Default is |
hex_bins |
A numeric value for the number of hex bins.
Default is |
hex_binwidth |
A numeric value for the hex bin width.
Default is |
label |
Whether to show group labels in |
label_size |
A numeric value for the label text size.
Default is |
label_fg |
A character string for the label text color.
Default is |
label_bg |
A character string for the label background color.
Default is |
label_bg_r |
A numeric value for the label background corner
radius ratio. Default is |
label_repel |
Whether to repel labels from each other and from
data points. Default is |
label_repulsion |
A numeric value for the repulsion force.
Default is |
label_pt_size |
A numeric value for the label anchor point size.
Default is |
label_pt_color |
A character string for the label anchor point
color. Default is |
label_segment_color |
A character string for the label connector
line color. Default is |
label_insitu |
Whether to place raw group names as labels
instead of numeric indices. Default is |
label_pos |
A character string or function specifying how label
positions are computed per group. Options: |
graph |
Graph/network edge data for |
graph_x |
A character string for the x start coordinate column in the graph data. |
graph_y |
A character string for the y start coordinate column in the graph data. |
graph_xend |
A character string for the x end coordinate column in the graph data. |
graph_yend |
A character string for the y end coordinate column in the graph data. |
graph_value |
A character string for the edge weight column in the graph data. |
edge_size |
A numeric vector of length 2 specifying the line width
range for graph edges. Default is |
edge_alpha |
A numeric value for graph edge transparency.
Default is |
edge_color |
A character string for the graph edge color.
Default is |
Details
SpatImagePlotRender a
SpatRasteras a raster image. Supports single-layer continuous values (with gradient fill) and 3-channel RGB data (with automatic color identity scaling).SpatMasksPlotRender a
SpatRasteras a categorical mask overlay. Zero-valued cells are treated as transparent background; optional polygon borders can be added around mask regions.SpatShapesPlotRender spatial shapes (polygons) from a
SpatVectoror a data frame of vertex coordinates. Supports single and multi-column fill mapping with automatic faceting.SpatPointsPlotRender spatial points from a data frame with support for color/size/fill mapping, hex binning, rasterized rendering, network/graph overlays, labels, and point highlighting.
Value
A ggplot object with height and width
attributes when return_layer = FALSE (the default). When
return_layer = TRUE, a list of ggplot layers with a
"scales" attribute is returned. When faceted via multiple
fill_by or color_by columns, a faceted ggplot
is returned.
Rendering Pipeline for SpatImagePlot
-
Extent cropping — if
extis provided, theSpatRasteris cropped viaterra::crop(). An error is raised if no cells remain within the extent. -
Auto-rasterization — if the raster exceeds 1e6 cells (or
raster = TRUE), the raster is aggregated viaterra::aggregate()to a target resolution ofraster_dpi. -
Y-axis flipping — when
flip_y = TRUE, the raster is flipped vertically via.flip_y()and its y-extent is negated so that axis labels can be displayed with reversed sign. -
RGB detection — if the raster has exactly 3 layers, they are treated as red/green/blue channels: each channel is rescaled to 0–255 and combined into a hex color via
rgb(). Ascale_fill_identity()is used with no legend guide. -
Single-layer rendering — otherwise, the raster is converted to an x/y/value data frame and rendered via
geom_raster()withscale_fill_gradientn(). -
Layer return or full assembly — if
return_layer = TRUE, the list of layers (with a"scales"attribute set to"fill") is returned. Otherwise,.wrap_spatial_layers()assembles a complete ggplot withcoord_sf(expand = 0), theme, labels, legend, and dimension attributes.
Rendering Pipeline for SpatMasksPlot
-
Extent cropping — if
extis provided, theSpatRasteris cropped viaterra::crop(). -
Y-axis flipping — when
flip_y = TRUE, the raster is flipped vertically and its y-extent is negated. -
Background masking — cells with value 0 are set to
NAso they render as transparent viana.value = "transparent". -
Raster layer — the mask is converted to an x/y/value data frame and rendered via
geom_raster()with a gradient fill scale. -
Optional borders — when
add_border = TRUE, the mask values are polygonized viaterra::as.polygons(), converted to sf, and overlaid as unfilledgeom_sf()with the specifiedborder_color,border_size, andborder_alpha. -
Layer return or full assembly — if
return_layer = TRUE, the layers are returned; otherwise,.wrap_spatial_layers()creates the complete ggplot.
Rendering Pipeline for SpatPointsPlot
-
Column resolution —
xandycoordinates are resolved from the data, auto-detecting common column names ("x","X","sdimx", etc. for x;"y","Y","sdimy", etc. for y) when not explicitly provided. -
Extent cropping — if
extis provided, rows outside the extent are filtered. -
Y-axis flipping — when
flip_y = TRUE, the y coordinate column is negated via.flip_y(). -
Multi-column faceting — when
color_byhas multiple columns (all numeric), the data is reshaped to long format with a.facet_varcolumn and faceted viafacet_plot(). -
Cutoff winsorization — for numeric
color_by, values outside[lower_cutoff, upper_cutoff](derived from quantiles or explicit values) are clamped to the nearest cutoff. -
Graph / network edges — if
graphis provided, edges are resolved from an adjacency matrix, data.frame, or data attribute, and rendered asgeom_segment()segments with line width proportional to edge weight. -
Main point layer — one of three rendering modes:
- Regular
(
hex = FALSE,raster = FALSE) —geom_point()with shape, size, color, and fill aesthetic mappings. Shapes 21–25 support separate fill and border colors.- Hex
(
hex = TRUE) —geom_hex()orstat_summary_hex()for binned aggregation of numericcolor_byvalues.- Raster
(
raster = TRUE) —scattermore::geom_scattermore()for efficient rendering of large datasets (>1e6 rows).
-
Highlight — if
highlightis specified, highlighted points are overlaid as larger, colored markers usinggeom_point()orscattermore::geom_scattermore(). -
Labels — if
label = TRUEandcolor_byis a categorical column, group centroid positions are computed viaaggregate()with thelabel_posfunction, and labels are rendered viaggrepel::geom_text_repel()with optional background styling and repulsion. -
Layer return or full assembly — if
return_layer = TRUE, the layers are returned; otherwise,.wrap_spatial_layers()creates the complete ggplot andfacet_plot()is applied when multi-column faceting is active.
Examples
set.seed(8525)
# --- SpatImagePlot ---
# Generate a sample SpatRaster
r <- terra::rast(
nrows = 50, ncols = 40, vals = runif(2000),
xmin = 0, xmax = 40, ymin = 0, ymax = 50,
crs = ""
)
SpatImagePlot(r)
SpatImagePlot(r, raster = TRUE, raster_dpi = 20)
SpatImagePlot(r, alpha = 0.5, theme = "theme_blank",
theme_args = list(add_coord = FALSE), fill_name = "value")
SpatImagePlot(r, ext = c(0, 10, 0, 10), flip_y = FALSE, palette = "viridis")
# --- SpatMasksPlot ---
m <- terra::rast(
nrows = 50, ncols = 40,
vals = sample(c(1:5, NA), 2000, replace = TRUE, prob = c(rep(0.04, 5), 0.8)),
xmin = 0, xmax = 40, ymin = 0, ymax = 50,
crs = ""
)
SpatMasksPlot(m, border_color = "red")
SpatMasksPlot(m, ext = c(0, 15, 0, 20), add_border = FALSE,
palreverse = TRUE, fill_name = "value")
# --- SpatShapesPlot ---
polygons <- data.frame(
id = paste0("poly_", 1:10),
cat = sample(LETTERS[1:3], 10, replace = TRUE),
feat1 = rnorm(10),
feat2 = rnorm(10),
geometry = c(
'POLYGON((64.6 75.3,66.0 70.5,66.4 70.2,67.0 69.8,72.8 70.4,64.6 75.3))',
'POLYGON((56.7 63.0,52.3 65.6,48.0 63.2,51.2 55.7,57.1 59.2,56.7 63.0))',
'POLYGON((9.9 16.5,9.3 15.9,8.0 13.1,11.5 7.8,17.8 11.3,9.9 16.5))',
'POLYGON((64.9 37.2,60.3 37.4,57.6 31.7,58.9 29.3,64.0 28.1,64.9 37.2))',
'POLYGON((30.5 49.1,22.4 46.5,22.4 43.9,30.9 41.9,31.6 42.9,30.5 49.1))',
'POLYGON((78.3 57.8,70.5 61.6,71.6 52.7,72.2 52.5,77.4 54.5,78.3 57.8))',
'POLYGON((41.8 23.8,41.3 25.9,41.0 26.4,36.5 28.7,35.8 28.6,41.8 23.8))',
'POLYGON((15.7 75.9,14.2 74.4,15.7 67.5,23.0 69.8,23.4 71.7,15.7 75.9))',
'POLYGON((80.7 37.4,75.3 31.3,77.1 28.5,82.5 28.0,83.1 28.5,80.7 37.4))',
'POLYGON((15.5 37.8,14.4 38.6,7.3 32.6,8.3 30.9,15.1 30.2,15.5 37.8))'
)
)
polygons <- terra::vect(polygons, crs = "EPSG:4326", geom = "geometry")
SpatShapesPlot(polygons)
SpatShapesPlot(polygons, ext = c(0, 20, 0, 20))
SpatShapesPlot(polygons, highlight = 'cat == "A"', highlight_color = "red2")
SpatShapesPlot(polygons, border_color = "red", border_size = 2)
SpatShapesPlot(polygons, fill_by = "cat", fill_name = "category")
# Let border color be determined by fill
SpatShapesPlot(polygons, fill_by = "cat", alpha = 0.6, border_color = TRUE)
SpatShapesPlot(polygons, fill_by = "feat1")
SpatShapesPlot(polygons, fill_by = c("feat1", "feat2"), palette = "RdYlBu")
# --- SpatPointsPlot ---
# create some random points in the above polygons
points <- data.frame(
id = paste0("point_", 1:30),
gene = sample(LETTERS[1:3], 30, replace = TRUE),
feat1 = runif(30, 0, 100),
feat2 = runif(30, 0, 100),
size = runif(30, 1, 5),
x = c(
61.6, 14.3, 12.7, 49.6, 74.9, 58.9, 13.9, 24.7, 16.9, 15.6,
72.4, 60.1, 75.4, 14.9, 80.3, 78.8, 16.7, 27.6, 48.9, 52.5,
12.9, 11.8, 50.4, 25.6, 10.4, 51.9, 73.4, 26.8, 50.4, 60.0
),
y = c(
32.1, 12.8, 33.2, 59.9, 57.8, 31.9, 10.1, 46.8, 75.3, 69.0,
60.0, 29.4, 54.2, 34.2, 35.3, 33.1, 74.7, 48.0, 63.2, 59.2,
9.2, 15.1, 64.5, 47.1, 11.4, 60.1, 54.1, 44.5, 61.9, 30.3
)
)
SpatPointsPlot(points)
SpatPointsPlot(points, color_by = "gene", size_by = "size", shape = 22,
border_size = 1)
SpatPointsPlot(points, raster = TRUE, raster_dpi = 30, color_by = "feat1")
SpatPointsPlot(points, color_by = c("feat1", "feat2"), size_by = "size")
SpatPointsPlot(points, color_by = "feat1", upper_cutoff = 50)
SpatPointsPlot(points, color_by = "feat1", hex = TRUE)
SpatPointsPlot(points, color_by = "gene", label = TRUE)
SpatPointsPlot(points, color_by = "gene", highlight = 1:20,
highlight_color = "red2", highlight_stroke = 0.8)
# --- Graph/Network functionality ---
# Create a simple adjacency matrix for demonstration
set.seed(8525)
graph_mat <- matrix(0, nrow = 30, ncol = 30)
# Add some random connections with weights
for(i in 1:30) {
neighbors <- sample(setdiff(1:30, i), size = sample(2:5, 1))
graph_mat[i, neighbors] <- runif(length(neighbors), 0.1, 1)
}
rownames(graph_mat) <- colnames(graph_mat) <- rownames(points)
attr(points, "graph") <- graph_mat
SpatPointsPlot(points, color_by = "gene", graph = "@graph",
edge_color = "grey60", edge_alpha = 0.3)
SpatPointsPlot(points, color_by = "feat1", graph = graph_mat,
edge_size = c(0.1, 1), edge_alpha = 0.5)
# --- Use the `return_layer` argument to get the ggplot layers
ext = c(0, 40, 0, 50)
ggplot2::ggplot() +
SpatImagePlot(r, return_layer = TRUE, alpha = 0.2, ext = ext) +
SpatShapesPlot(polygons, return_layer = TRUE, ext = ext, fill_by = "white") +
SpatPointsPlot(points, return_layer = TRUE, ext = ext, color_by = "feat1") +
theme_box() +
ggplot2::coord_sf(expand = 0) +
ggplot2::scale_y_continuous(labels = function(x) -x)
Atomic split bar plot (internal)
Description
Core implementation for drawing a split (divergent / waterfall-style) bar
plot. Bars extend left (negative values) and right (positive values) from
a central zero line, with the y-axis listing categories. Bars can be
coloured by a categorical or continuous fill variable, and their opacity
can encode an additional numeric variable via alpha_by.
This is the workhorse behind the exported SplitBarPlot
(also aliased as WaterfallPlot).
Usage
SplitBarPlotAtomic(
data,
x,
y,
y_sep = "_",
flip = FALSE,
alpha_by = NULL,
alpha_reverse = FALSE,
alpha_name = NULL,
order_y = list(`+` = c("x_desc", "alpha_desc"), `-` = c("x_desc", "alpha_asc")),
bar_height = 0.9,
lineheight = 0.5,
max_charwidth = 80,
fill_by = NULL,
fill_by_sep = "_",
fill_name = NULL,
direction_name = "direction",
direction_pos_name = "positive",
direction_neg_name = "negative",
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
facet_by = NULL,
facet_scales = "free_y",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
aspect.ratio = 1,
x_min = NULL,
x_max = NULL,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_empty = FALSE,
keep_na = FALSE,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the numeric column for the x-axis. Values determine bar direction: positive → right, negative → left. |
y |
A character string (or vector) specifying the column(s) for the
category axis. Each unique value becomes a bar. Multiple columns are
concatenated with |
y_sep |
A character string to join multiple |
flip |
Logical; if |
alpha_by |
A character string naming a numeric column to encode as
bar opacity. Default |
alpha_reverse |
Logical; if |
alpha_name |
A character string for the alpha legend title. |
order_y |
A named list controlling the vertical ordering of bars.
Keys are |
bar_height |
A numeric value (0–1) specifying the bar height as a fraction of the available category slot. |
lineheight |
A numeric value controlling the line height of wrapped category labels. |
max_charwidth |
An integer specifying the maximum character width for wrapping category labels. |
fill_by |
A character string (or vector) naming the column(s) for
bar fill colour. If |
fill_by_sep |
A character string to join multiple |
fill_name |
A character string for the fill legend title. |
direction_name |
A character string naming the internal direction
column (used in legends). Default |
direction_pos_name |
A character string labelling the positive
direction in the legend. Default |
direction_neg_name |
A character string labelling the negative
direction in the legend. Default |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
x_min, x_max |
Numeric limits for the x-axis. When |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
... |
Additional arguments. |
Value
A ggplot object, possibly faceted, with height
and width attributes (in inches) attached.
Architecture
-
Column resolution —
x,y,fill_by,alpha_by, andfacet_byare validated viacheck_columns. Multi-columnyandfill_byare concatenated with their respective separators. -
Direction assignment — a
direction_namecolumn is created from the sign ofx, assigning each row to the positive or negative group (customisable viadirection_pos_name/direction_neg_name). -
Fill resolution — if
fill_byisNULL, the direction column is used as the fill (two-colour palette). Categorical fills use a discrete colour scale; numeric fills useprepare_continuous_color_scale()with quantile / cutoff clamping andscale_fill_gradientn(). -
Alpha by — when
alpha_byis provided, bar opacity encodes an additional numeric variable viascale_alpha_continuous(). -
Ordering —
order_yis a named list controlling the vertical ordering of bars. The keys"+"and"-"specify separate orderings for positive and negative bars; key"*"applies a single ordering to all bars. Values are character vectors of ordering criteria:"x_asc","x_desc","alpha_asc","alpha_desc". -
Empty level padding — when
keep_empty_y = TRUE, missing y-levels are padded per facet (or globally) with zero-height bars so they still appear on the axis. -
Text labels — category names are drawn beside the bars via
geom_text()at the zero line. When flipped, labels are rotated 90°. Long labels are wrapped viastr_wrap()usingmax_charwidth. -
Plot assembly — the ggplot is built with
geom_vline(xintercept = 0)for the centre line,geom_col()for bars, and the appropriate fill / alpha scales. -
Dimension calculation —
calculate_plot_dimensions()computes dimensions from the number of y categories, scaled bybar_height / 4. Flipping adjusts the aspect ratio. -
Faceting —
facet_plot()wraps the result, defaulting tofacet_scales = "free_y".
Trend plot
Description
Draws a trend plot combining stacked bars with a semi-transparent area background to show how one or more groups accumulate across a discrete x-axis variable. This hybrid style sits between a bar plot and an area plot: it preserves the discrete category separation of bars while softening the visual with an area fill, making trends across categories easier to perceive.
The function supports count aggregation (omit y to plot
observation counts per x-category), proportion scaling
(scale_y = TRUE normalises each x position to 100\
colour control, faceting, and splitting into separate sub-plots via
split_by.
Usage
TrendPlot(
data,
x,
y = NULL,
x_sep = "_",
split_by = NULL,
split_by_sep = "_",
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
scale_y = FALSE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
x_sep |
A character string used to join multiple |
split_by |
The column(s) to split the data by and produce separate
sub-plots. Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
group_name |
A character string used as the fill legend title.
When |
scale_y |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
seed |
A numeric seed for reproducibility. Passed to
|
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default |
axes |
A character string specifying how axes should be treated across
the combined layout (passed to |
axis_titles |
A character string specifying how axis titles should be
treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should be
collected across panels. Default |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments. |
Value
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by workflow
When split_by is provided:
-
check_keep_na()andcheck_keep_empty()normalise thekeep_na/keep_emptyarguments for all columns (x,split_by,group_by,facet_by). The
split_bycolumn is validated and its NA / empty levels are processed viaprocess_keep_na_empty(). It is then removed from the per-columnkeep_na/keep_emptylists.The data frame is split by
split_by(preserving level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
TrendPlotAtomic()is called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
See Also
AreaPlot for a pure stacked area plot.
Examples
data <- data.frame(
x = factor(rep(c("A", "B", NA, "D"), 3), levels = LETTERS[1:4]),
y = c(1, 3, 6, 5, 4, 2, 5, 7, 8, 9, 4, 8),
group = factor(rep(c("F1", NA, "F3"), each = 4), levels = c("F1", "F2", "F3"))
)
# Basic trend plot with grouping
TrendPlot(data, x = "x", y = "y", group_by = "group")
# Scaled to proportions
TrendPlot(data, x = "x", y = "y", group_by = "group",
scale_y = TRUE)
# Split into sub-plots (no group_by -- single-colour fill)
TrendPlot(data, x = "x", y = "y", split_by = "group")
# Per-split palettes
TrendPlot(data, x = "x", y = "y", split_by = "group",
palette = c(F1 = "Set1", F3 = "Dark2"))
# How keep_na and keep_empty work
TrendPlot(data, x = "x", y = "y", group_by = "group",
keep_na = TRUE, keep_empty = TRUE)
TrendPlot(data, x = "x", y = "y", group_by = "group",
keep_na = TRUE, keep_empty = list(x = FALSE, group = 'level'))
# Faceting
TrendPlot(data, x = "x", y = "y", facet_by = "group",
keep_na = TRUE, keep_empty = list(x = FALSE, group = 'level'))
Atomic trend plot (internal)
Description
Core implementation for drawing a single trend plot. This is the workhorse
behind the exported TrendPlot function – it takes a single
data frame (no split_by support) and returns a ggplot object.
A trend plot combines stacked bars (geom_col()) with
a semi-transparent area background (geom_area()) to
show how one or more groups accumulate across a discrete x-axis. This hybrid
style sits between a bar plot and an area plot, preserving the discrete
category separation of bars while softening the visual with an area fill.
The function supports count aggregation (omit y to plot observation
counts per x-category), proportion scaling (scale_y = TRUE normalises
each x position to 100\
Usage
TrendPlotAtomic(
data,
x,
y = NULL,
x_sep = "_",
group_by = NULL,
group_by_sep = "_",
group_name = NULL,
scale_y = FALSE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = waiver(),
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_empty = FALSE,
keep_na = FALSE,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name to plot on the
x-axis. Must be character or factor. Multiple columns can be provided;
they are concatenated with |
y |
A character string specifying the numeric column for the y-axis.
When |
x_sep |
A character string used to join multiple |
group_by |
A character vector of column names to fill the bars and
areas by. Each unique combination becomes a separate stacked segment.
Multiple columns are concatenated with |
group_by_sep |
A character string to separate concatenated
|
group_name |
A character string used as the fill legend title.
When |
scale_y |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
Column resolution –
x,y,group_by, andfacet_byare validated and transformed viacheck_columns. Multi-column inputs forxandgroup_byare concatenated into single columns using their respective separators (x_sep,group_by_sep). -
Count aggregation – when
y = NULL, the count of observations in each unique (x,group_by,facet_by) combination is computed as a new.countcolumn. Factor levels are preserved after aggregation. -
Proportion scaling – when
scale_y = TRUE, the y-values are divided by the sum within each (x,facet_by) group, producing a proportion (0–1). Percent labels are used automatically on the y-axis. -
NA / empty-level handling –
process_keep_na_empty()applieskeep_naandkeep_emptypolicies. Per-columnkeep_emptysettings are extracted forx,group_by, andfacet_byindependently. The facet columns must have identicalkeep_emptyvalues. Note thatkeep_empty = TRUEis not supported globally because empty categories would break the continuity of the x-axis. -
Group fill setup – when
group_by = NULL, a dummy.fillfactor is created so the single group still draws with the first palette colour. The legend is suppressed (legend.position = "none"). -
Data completion –
complete()pads allxbygroup_by(byfacet_by) combinations withy = 0. This preventsgeom_area()from interpolating across missing groups, which would otherwise cause stacked areas to exceed the correct total. -
Area layer construction – the completed data is expanded by duplicating each row and offsetting the x-axis positions by
\pm 0.2on a numeric scale, creating discrete-width area strips that align perfectly with the bars. -
Colour mapping –
palette_this()assigns colours to allgroup_bylevels, includingNA(defaulting to"grey80"). -
Plot assembly – the
ggplotobject is built withgeom_area()(at halfalpha, grey outline) as a background fill, overlaid withgeom_col()(fullalpha, black outline, width 0.4) as the foreground bars. Both layers useposition_stack(vjust = 0.5). The x-axis usesscale_x_discrete()and the y-axis usesscale_y_continuous()(percent labels when scaled). The fill scaledropargument is controlled bykeep_empty_group. -
Dimension calculation –
calculate_plot_dimensions()computes plot height and width from the x-axis category count,aspect.ratio, and legend metrics. The base height increases for plots with 10 or more x categories (from 4.5 to 6.5 inches). The resultingheightandwidthattributes are stored on theggplotobject. -
Faceting –
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided, respecting thekeep_emptysetting for facet variables.
UpSet Plot
Description
Draws an UpSet plot visualising set intersections and set sizes. The plot comprises:
A horizontal bar chart showing the size of each intersection, filled by the intersection count.
A combination matrix (rows = sets, columns = intersections) with membership dots and connecting lines.
A set-size bar chart on the left of the matrix (added automatically by
ggupset).
The function accepts data in four formats:
-
List — a named list of element vectors (one per set).
-
Long — a data frame with one row per (set, element) pair.
-
Wide — a data frame where each row is an element and each set has its own logical or 0/1 membership column.
-
UpsetPlotData — a pre-processed object from
prepare_upset_data().
Supports splitting into sub-plots via split_by, per-split colour
palettes and legend control, and combining sub-plots via patchwork.
Usage
UpsetPlot(
data,
in_form = c("auto", "long", "wide", "list", "upset"),
split_by = NULL,
split_by_sep = "_",
group_by = NULL,
group_by_sep = "_",
id_by = NULL,
label = TRUE,
label_fg = "black",
label_size = NULL,
label_bg = "white",
label_bg_r = 0.1,
palette = "Blues",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
specific = TRUE,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
aspect.ratio = 0.6,
legend.position = "right",
legend.direction = "vertical",
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
combmatrix_gap = 6,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
in_form |
A character string specifying the input format. One of
|
split_by |
The column(s) to split the data by and produce separate
sub-plots. Only supported for |
split_by_sep |
A character string to separate concatenated
|
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
id_by |
A character string specifying the column name for instance
identifiers. Required for long format; optional for wide format (a
synthetic |
label |
A logical value. When |
label_fg |
A character string specifying the colour of the label text.
Default: |
label_size |
A numeric value specifying the size of the label text.
Default: |
label_bg |
A character string specifying the background fill colour of
the label. Default: |
label_bg_r |
A numeric value specifying the corner radius of the label
background, passed to |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
specific |
A logical value. When |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default |
seed |
A numeric seed for reproducibility. Passed to
|
combmatrix_gap |
A numeric value specifying the gap between rows of the
combination matrix, measured at |
axes |
A character string specifying how axes should be treated across
the combined layout (passed to |
axis_titles |
A character string specifying how axis titles should be
treated across the combined layout. Defaults to |
guides |
A character string specifying how legends should be collected
across panels (passed to |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments. |
Value
A ggplot object, a patchwork object, or a named list
of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by Workflow
When split_by is provided:
-
Guard —
split_byis only supported fordata.frameinput. Ifdatais a list (or other non-data.frame type) andsplit_byis non-NULL, an error is raised. -
Column validation —
check_columns()resolves thesplit_bycolumn(s) withforce_factor = TRUEandallow_multi = TRUE. Multiple columns are concatenated withsplit_by_sep. -
Data splitting — empty factor levels in
split_byare dropped viadroplevels(), then the data frame is split bysplit_by(level order is preserved). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...". -
Per-split resolution —
check_palette(),check_palcolor(), andcheck_legend()resolve per-splitpalette,palcolor,legend.position, andlegend.direction. -
Atomic dispatch —
UpsetPlotAtomicis called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles. When in wide mode (in_formis"auto"or"wide") andgroup_byisNULL, the set columns are auto-detected as all columns exceptid_byandsplit_by. -
Combination — Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
# ---- list input -------------------------------------------------------
data <- list(
A = 1:5,
B = 2:6,
C = 3:7,
D = 4:8
)
UpsetPlot(data)
UpsetPlot(data, label = FALSE)
UpsetPlot(data, palette = "Reds", specific = FALSE)
# ---- long-format data frame ------------------------------------------
data_long <- data.frame(
group_by = factor(
c(rep("A", 5), rep("B", 5), rep("C", 5), rep("D", 5)),
levels = c("A", "B", "C", "D")
),
id_by = c(1:5, 2:6, 3:7, 4:8)
)
UpsetPlot(data_long, in_form = "long", group_by = "group_by", id_by = "id_by")
# ---- wide-format data frame ------------------------------------------
data <- data.frame(
id = LETTERS[1:10],
B = c(1, 0, 1, 1, 0, 0, 1, 0, 1, 0),
A = c(1, 1, 1, 0, 0, 1, 0, 0, 1, 0),
D = c(1, 0, 0, 1, 1, 0, 0, 1, 0, 1),
C = c(0, 1, 1, 0, 1, 0, 1, 0, 1, 0)
)
UpsetPlot(data, in_form = "wide", id_by = "id", n_intersections = 4)
Atomic UpSet plot (internal)
Description
Core implementation for drawing a single UpSet plot. This is the internal
workhorse behind the exported UpsetPlot function — it takes a
single data partition (no split_by support) and returns a
ggplot object. The plot comprises three visual components:
A horizontal bar chart (top) showing the size of each intersection, with bars filled by a gradient of intersection count.
A set-size bar chart (left) showing the total number of elements in each set (added automatically by
ggupset).A combination matrix (bottom) where rows are sets, columns are intersections, and dots indicate set membership. Connected dots trace the intersection pattern.
Usage
UpsetPlotAtomic(
data,
in_form = "auto",
group_by = NULL,
group_by_sep = "_",
id_by = NULL,
label = TRUE,
label_fg = "black",
label_size = NULL,
label_bg = "white",
label_bg_r = 0.1,
palette = "material-indigo",
palcolor = NULL,
palreverse = FALSE,
alpha = 1,
specific = TRUE,
combmatrix_gap = 6,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
aspect.ratio = 0.6,
legend.position = "right",
legend.direction = "vertical",
levels = NULL,
...
)
Arguments
data |
A data frame. |
in_form |
A character string specifying the input format. One of
|
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
id_by |
A character string specifying the column name for instance
identifiers. Required for long format; optional for wide format (a
synthetic |
label |
A logical value. When |
label_fg |
A character string specifying the colour of the label text.
Default: |
label_size |
A numeric value specifying the size of the label text.
Default: |
label_bg |
A character string specifying the background fill colour of
the label. Default: |
label_bg_r |
A numeric value specifying the corner radius of the label
background, passed to |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
alpha |
A numeric value specifying the transparency of the plot. |
specific |
A logical value. When |
combmatrix_gap |
A numeric value specifying the gap between rows of the
combination matrix, measured at |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
levels |
A character vector of set levels to include, in display order.
When |
... |
Additional arguments passed to |
Value
A ggplot object with height and width attributes
(in inches).
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Data preparation —
prepare_upset_data()converts the input into the internalUpsetPlotDataformat with anIntersectionlist-column (set-membership labels per element) and a"group_order"attribute for set ordering. -
Text scale —
base_sizefromtheme_args(default 12) drives atext_size_scalethat proportionally scales the combination-matrix row gap, label sizes, and point sizes. -
Bar geom —
geom_bar()counts rows per intersection. Bars are filled by count viascale_fill_gradientn()with colours frompalette_this(). -
Bar labels — when
label = TRUE,geom_text_repel()places count labels above each bar, with configurable foreground, background, and size. -
Scale x upset —
ggupset::scale_x_upset(...)is called, returning two components: aScaleUpset(index[[1]]) and aCoordCombMatrix(index[[2]]). Only the scale is applied; the bundled coord is discarded to avoid a "Coordinate system already present" conflict. -
Labels and theme —
labs()sets title, subtitle, and axis text.do_call(theme, theme_args)applies the chosen theme. Aspect ratio, legend position, legend direction, and grid lines are configured. -
Combination matrix —
ggupset::axis_combmatrix()builds the lower panel via anoverride_plotting_function:Reorders rows to match
group_order(reversed for top-to-bottom set listing).Alternating row backgrounds via
geom_rect()with white /#F7F7F7fills.Set-membership dots (
geom_point()) in black for present and#E0E0E0for absent.Connecting lines (
geom_line()) through observed dots to trace the intersection pattern.
-
Matrix theme —
ggupset::theme_combmatrix()applies the combination-matrix appearance withcombmatrix_gapbetween rows (scaled bytext_size_scale). -
Dimension calculation —
calculate_plot_dimensions()computes height fromn_setsand width fromn_intersections, both passed via...(default 99).aspect.ratiois used as a standard H/W coupling withx_scale_factor = 0.6. An additional width adjustment accounts for set-label character width.
Cell velocity plot
Description
Plots RNA velocity vectors on a low-dimensional embedding (e.g., UMAP, t-SNE) to visualize the direction and magnitude of cellular state transitions. Supports three visualization modes: raw arrows at each cell position, arrows on a regular grid, and streamline paths. Optionally colors arrows by cell metadata groups.
Usage
VelocityPlot(
embedding,
v_embedding,
plot_type = c("raw", "grid", "stream"),
split_by = NULL,
group_by = NULL,
group_name = "Group",
group_palette = "Paired",
group_palcolor = NULL,
n_neighbors = NULL,
density = 1,
smooth = 0.5,
scale = 1,
min_mass = 1,
cutoff_perc = 5,
arrow_angle = 20,
arrow_color = "black",
arrow_alpha = 1,
keep_na = FALSE,
keep_empty = FALSE,
streamline_l = 5,
streamline_minl = 1,
streamline_res = 1,
streamline_n = 15,
streamline_width = c(0, 0.8),
streamline_alpha = 1,
streamline_color = NULL,
streamline_palette = "RdYlBu",
streamline_palcolor = NULL,
palreverse = FALSE,
streamline_bg_color = "white",
streamline_bg_stroke = 0.5,
aspect.ratio = 1,
title = "Cell velocity",
subtitle = NULL,
xlab = NULL,
ylab = NULL,
legend.position = "right",
legend.direction = "vertical",
theme = "theme_this",
theme_args = list(),
return_layer = FALSE,
seed = 8525
)
Arguments
embedding |
A matrix or data frame of dimension n_obs x n_dim specifying the low-dimensional embedding coordinates (e.g., UMAP, t-SNE) of the cells. The first two columns are used for the x and y axes. |
v_embedding |
A matrix or data frame of dimension n_obs x n_dim specifying the velocity vectors for each cell. Must have the same dimensions as |
plot_type |
A character string specifying the visualization method. |
split_by |
Not supported for VelocityPlot. Setting this parameter will raise an error. |
group_by |
An optional vector of the same length as the number of rows in |
group_name |
A character string specifying the legend title for the grouping variable. Default is |
group_palette |
A character string specifying the color palette to use for the grouping variable. Passed to |
group_palcolor |
An optional character vector of specific colors for the grouping variable. If |
n_neighbors |
An integer value specifying the number of nearest neighbors for computing grid velocities. Only used when |
density |
A numeric value specifying the grid density along each dimension. Only used when |
smooth |
A numeric value specifying the standard deviation multiplier for the Gaussian kernel when averaging cell velocities onto grid points. Only used when |
scale |
A numeric value specifying the scaling factor for the velocity vectors. Applied to raw and grid arrows. For |
min_mass |
A numeric value specifying the minimum mass threshold for retaining grid points. Only used when |
cutoff_perc |
A numeric value specifying the percentile cutoff for removing low-density grid points. Only used when |
arrow_angle |
A numeric value specifying the angle of the arrowheads in degrees. Applied to |
arrow_color |
A character string specifying the color of the velocity arrows. For |
arrow_alpha |
A numeric value between 0 and 1 specifying the transparency of the velocity arrows. Only used when |
keep_na |
A logical or character value specifying how to handle NA values in |
keep_empty |
One of |
streamline_l |
A numeric value specifying the integration length of the streamlines. Passed to |
streamline_minl |
A numeric value specifying the minimum streamline length. Shorter streamlines are not drawn. Passed to |
streamline_res |
A numeric value specifying the resolution of the streamline integration. Passed to |
streamline_n |
A numeric value specifying the number of streamlines to draw. Passed to |
streamline_width |
A numeric vector of length 2 specifying the range of line widths for streamlines. Passed to |
streamline_alpha |
A numeric value between 0 and 1 specifying the transparency of the velocity streamlines. Default is 1. |
streamline_color |
An optional character string specifying a fixed color for streamlines. When |
streamline_palette |
A character string specifying the color palette for streamline velocity magnitude. Passed to |
streamline_palcolor |
An optional character vector of specific colors for the streamline velocity gradient. If |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
streamline_bg_color |
A character string specifying the background (outline) color applied to streamlines to create a stroke effect. Default is |
streamline_bg_stroke |
A numeric value specifying the additional line width of the background stroke relative to the foreground streamline. Default is 0.5. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
return_layer |
A logical value indicating whether to return only the ggplot layers instead of the full assembled plot. When |
seed |
The random seed to use. Default is 8525. |
Value
A ggplot object representing the cell velocity plot, with height and width attributes set for consistent rendering. If return_layer = TRUE, returns a list of ggplot layers instead.
Rendering Pipeline
The VelocityPlot function proceeds through the following steps:
Input validation — Verifies that
embeddingandv_embeddingare matrices or data frames of equal dimensions, thatgroup_bymatches the number of rows (if provided), and thatsplit_byisNULL(unsupported and raises an error).Axis label resolution — Uses the column names of
embeddingas axis labels, falling back to"Reduction 1"and"Reduction 2"when column names areNULL.Grouping setup — Converts
group_byto a factor and applieskeep_na/keep_emptylogic to filter or recode missing values and empty factor levels.Plot-type dispatch — Branches on
plot_type:raw — Optionally subsamples cells when
density < 1, scales velocity vectors byscale, computes arrow lengths proportional to the embedding range, and rendersgeom_segmentwith arrowheads. Whengroup_byis provided, arrows are colored by group usinggroup_palette.grid — Delegates to
.compute_velocity_on_gridto interpolate the sparse cell velocities onto a regular grid, then rendersgeom_segmentwith arrowheads at each grid point.group_byis ignored with a warning.stream — Delegates to
.compute_velocity_on_gridwithadjust_for_stream = TRUE, then renders smooth streamline paths viageom_streamline. Whenstreamline_coloris provided, streamlines use a fixed color with a background stroke; whenNULL, streamlines are colored by velocity magnitude usingstreamline_palette.group_byis ignored with a warning.
Layer return or plot assembly — If
return_layer = TRUE, returns the list of ggplot layers. Otherwise, constructs a fullggplotobject with labels, theme, aspect ratio, legend configuration, andheight/widthattributes viacalculate_plot_dimensions().
See Also
Examples
data(dim_example)
dim_example$clusters[dim_example$clusters == "Ductal"] <- NA
# Basic velocity plot with group coloring
VelocityPlot(dim_example[, 1:2], dim_example[, 3:4], group_by = dim_example$clusters)
# Handle NA groups with keep_na / keep_empty
VelocityPlot(dim_example[, 1:2], dim_example[, 3:4], group_by = dim_example$clusters,
keep_na = TRUE, keep_empty = TRUE)
VelocityPlot(dim_example[, 1:2], dim_example[, 3:4], group_by = dim_example$clusters,
keep_na = TRUE, keep_empty = 'level')
VelocityPlot(dim_example[, 1:2], dim_example[, 3:4], group_by = dim_example$clusters,
keep_na = TRUE, keep_empty = FALSE)
Venn / Euler diagram
Description
Draws Venn or Euler diagrams that visualise the overlap relationships among
multiple sets. Supports four input formats: long (one row per element-set
pair), wide (logical/0-1 columns per set), a named list (element vectors
per set), and a pre-computed VennPlotData object.
Intersection regions can be filled by a continuous colour gradient encoding
the element count (fill_mode = "count" / "count_rev") or by
blended set colours (fill_mode = "set"). Region labels can display
counts, percentages, both, or a custom function. Set labels always show
the set name and its total element count.
Use split_by to produce separate Venn diagrams for each level of a
grouping variable. Note that split_by is only supported when
data is a data frame (list and VennPlotData inputs cannot be
split).
Usage
VennDiagram(
data,
in_form = c("auto", "long", "wide", "list", "venn"),
split_by = NULL,
split_by_sep = "_",
group_by = NULL,
group_by_sep = "_",
id_by = NULL,
label = "count",
label_fg = "black",
label_size = NULL,
label_bg = "white",
label_bg_r = 0.1,
fill_mode = "count",
palreverse = FALSE,
fill_name = NULL,
palette = ifelse(fill_mode == "set", "Paired", "Blues"),
palcolor = NULL,
alpha = 1,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
legend.position = "right",
legend.direction = "vertical",
aspect.ratio = 1,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
seed = 8525,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
in_form |
A character string specifying the input format. One of
|
split_by |
The column(s) to split the data by and produce separate
Venn diagrams per subgroup. Only supported when |
split_by_sep |
A character string to separate concatenated
|
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
id_by |
A character string specifying the column name that identifies individual elements. Required for long-format data; ignored otherwise. |
label |
A character string or function controlling the text shown in each intersection region. One of:
|
label_fg |
A character string specifying the colour of the label text. |
label_size |
A numeric value specifying the font size of the label
text. When |
label_bg |
A character string specifying the background colour of the
label text (passed to |
label_bg_r |
A numeric value specifying the corner radius of the label
background rectangle (passed as |
fill_mode |
A character string specifying how intersection regions are coloured. One of:
|
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
fill_name |
A character string for the colour bar legend title when
|
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
when |
byrow |
Logical; fill the combined layout by row (default |
seed |
A numeric seed for reproducibility. Default |
axes, axis_titles |
Character strings specifying how axes and axis titles are handled across the combined layout. |
guides |
A character string specifying how legends are collected across panels in the combined layout. |
design |
A custom layout specification for the combined plot.
Passed to |
... |
Additional arguments. |
Value
A ggplot object (single split), a patchwork object
(combined sub-plots), or a named list of ggplot objects (when
combine = FALSE), each with height and width
attributes in inches.
split_by Workflow
When a non-NULL split_by is provided and the input is a
data frame:
-
Validation — an error is raised if
datais not a data frame (list andVennPlotDatainput cannot be split). -
Column resolution —
split_byis validated and optionally concatenated viacheck_columns()withforce_factor = TRUEandallow_multi = TRUE. -
Data splitting — the data frame is split by the unique levels of the
split_bycolumn, preserving factor level order. Empty levels are dropped viadroplevels(). -
Per-split colour and legend resolution —
check_palette(),check_palcolor(), andcheck_legend()resolve per-split palettes, custom colours, legend positions, and legend directions. -
Atomic dispatch —
VennDiagramAtomic()is called for each subset. Whentitleis a function, it receives the split level name for dynamic title generation. -
Combination — results are passed to
combine_plots()which returns a combinedpatchworkobject (whencombine = TRUE) or a named list of individual ggplot objects (whencombine = FALSE).
Examples
set.seed(8525)
data <- list(
A = sort(sample(letters, 8)),
B = sort(sample(letters, 8)),
C = sort(sample(letters, 8)),
D = sort(sample(letters, 8))
)
# Basic Venn diagram with count labels
VennDiagram(data)
# Fill by set membership (blended colours)
VennDiagram(data, fill_mode = "set")
# Show both count and percentage
VennDiagram(data, label = "both")
# Custom label function using set names
VennDiagram(data, label = function(df) df$name)
# Custom palette and transparency
VennDiagram(data, palette = "material-indigo", alpha = 0.6)
Atomic Venn / Euler diagram (internal)
Description
Core implementation for drawing a Venn or Euler diagram that visualises
the overlap relationships among multiple sets. Supports four input formats
(long, wide, list, and pre-computed VennPlotData) which are
normalised by prepare_venn_data() into the internal
VennPlotData representation used by ggVennDiagram.
Intersection regions can be filled either by a continuous colour gradient
based on the element count (fill_mode = "count" or "count_rev")
or by blended set colours (fill_mode = "set"). Region labels can
display the raw count, the percentage of total elements, both, nothing, or
a custom function result. Set labels always show the set name and its
total element count.
Usage
VennDiagramAtomic(
data,
in_form = "auto",
group_by = NULL,
group_by_sep = "_",
id_by = NULL,
label = "count",
label_fg = "black",
label_size = NULL,
label_bg = "white",
label_bg_r = 0.1,
fill_mode = "count",
palreverse = FALSE,
fill_name = NULL,
aspect.ratio = 1,
palette = ifelse(fill_mode == "set", "Paired", "Spectral"),
palcolor = NULL,
alpha = 1,
theme = "theme_this",
theme_args = list(),
title = NULL,
subtitle = NULL,
legend.position = "right",
legend.direction = "vertical",
...
)
Arguments
data |
A data frame. |
in_form |
A character string specifying the input format. One of
|
group_by |
A character string (or vector) specifying the column name(s)
that define the set membership. For |
group_by_sep |
The separator for multiple group_by columns. See |
id_by |
A character string specifying the column name that identifies individual elements. Required for long-format data; ignored otherwise. |
label |
A character string or function controlling the text shown in each intersection region. One of:
|
label_fg |
A character string specifying the colour of the label text. |
label_size |
A numeric value specifying the font size of the label
text. When |
label_bg |
A character string specifying the background colour of the
label text (passed to |
label_bg_r |
A numeric value specifying the corner radius of the label
background rectangle (passed as |
fill_mode |
A character string specifying how intersection regions are coloured. One of:
|
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
fill_name |
A character string for the colour bar legend title when
|
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
Data type detection —
detect_venn_datatype()identifies whetherdatais in long, wide, list, orVennPlotDataformat. -
Data preparation —
prepare_venn_data()converts the input into aVennPlotDataobject suitable for rendering by ggVennDiagram. -
Geometry extraction — ggVennDiagram utilities (
venn_regionedge(),venn_setedge(),venn_regionlabel(),venn_setlabel()) compute polygon vertices and label positions for all sets and their intersections. -
Fill resolution — When
fill_mode = "set",palette_this()assigns colours to each set; theblend_colors()helper blends the colours of overlapping sets for each intersection region. Whenfill_mode = "count"or"count_rev", a continuous gradient is applied across regions viascale_fill_gradientn()with a colour bar legend. -
Label computation — Region labels are formatted per the
labelparameter: raw count, percentage, both, none, or a custom function that receives a data frame with columns"id","X","Y","name","item", and"count". Set labels are formatted as"setName\n(count)". -
Plot assembly —
geom_polygon()draws filled regions;geom_path()draws set outlines; twogeom_text_repel()layers add region labels and set labels. Forfill_mode = "set", colours are mapped directly (no aesthetic mapping, no legend); for count modes, ascale_fill_gradientn()continuous scale is used. -
Theme and coordinate system —
coord_equal()enforces a square aspect ratio. The theme removes all axis text, ticks, titles, grid lines, and panel borders. The x-axis expansion is widened to accommodate set label text width. -
Dimension calculation —
calculate_plot_dimensions()computesheightandwidthattributes (in inches) frombase_height,aspect.ratio, and legend metrics. Whenfill_mode = "set", the legend position is forced to"none".
Volcano plot
Description
Produces a volcano plot — a scatter plot that displays statistical
significance (typically -log10 adjusted p-value) on the y-axis versus
magnitude of change (log2 fold change) on the x-axis. Points are coloured
automatically by significance category ("sig_pos_x",
"sig_neg_x", "insig") or by a user-supplied column. The
most significant features can be labelled automatically via
geom_text_repel(), and specific points can be
highlighted.
The function supports automatic labelling of top features (by
distance to origin), mirrored layout via
flip_negatives, x-axis trimming to reduce the influence
of extreme values, faceting, and splitting into
separate sub-plots via split_by with per-split colour palette and
legend control.
Usage
VolcanoPlot(
data,
x,
y,
ytrans = function(n) -log10(n),
color_by = NULL,
color_name = NULL,
xlim = NULL,
flip_negatives = FALSE,
x_cutoff = NULL,
y_cutoff = 0.05,
split_by = NULL,
split_by_sep = "_",
label_by = NULL,
x_cutoff_name = NULL,
y_cutoff_name = NULL,
x_cutoff_color = "red2",
y_cutoff_color = "blue2",
x_cutoff_linetype = "dashed",
y_cutoff_linetype = "dashed",
x_cutoff_linewidth = 0.5,
y_cutoff_linewidth = 0.5,
pt_size = 2,
pt_alpha = 0.5,
nlabel = 5,
labels = NULL,
label_size = 3,
label_fg = "black",
label_bg = "white",
label_bg_r = 0.1,
highlight = NULL,
highlight_color = "red",
highlight_size = 2,
highlight_alpha = 1,
highlight_stroke = 0.5,
trim = c(0, 1),
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
ytrans |
A function to transform the y-axis values before plotting.
The default |
color_by |
A character string specifying the column name to colour
the points by. When |
color_name |
A character string for the colour legend title when
|
xlim |
A numeric vector of length 2 to set the x-axis limits.
Passed to |
flip_negatives |
A logical value. When |
x_cutoff |
A numeric value specifying the x-axis significance
cutoff. Both the negative and positive of this value are used as
vertical threshold lines. When |
y_cutoff |
A numeric value specifying the y-axis significance
cutoff in the original (untransformed) scale. The value is
transformed by |
split_by |
The column(s) to split the data by and produce separate
sub-plots. Multiple columns are concatenated with |
split_by_sep |
A character string to separate concatenated
|
label_by |
A character string specifying the column whose values
are used as label text. When |
x_cutoff_name |
A character string for the x-cutoff legend entry.
When |
y_cutoff_name |
A character string for the y-cutoff legend entry.
When |
x_cutoff_color |
A character string specifying the colour of the
x-axis cutoff line(s). Default: |
y_cutoff_color |
A character string specifying the colour of the
y-axis cutoff line(s). Default: |
x_cutoff_linetype |
A character string specifying the linetype of
the x-axis cutoff line(s). Default: |
y_cutoff_linetype |
A character string specifying the linetype of
the y-axis cutoff line(s). Default: |
x_cutoff_linewidth |
A numeric value specifying the linewidth of
the x-axis cutoff line(s). Default: |
y_cutoff_linewidth |
A numeric value specifying the linewidth of
the y-axis cutoff line(s). Default: |
pt_size |
A numeric value specifying the point size for all data
points. Default: |
pt_alpha |
A numeric value in |
nlabel |
An integer specifying the number of top features to label
automatically. Points are ranked by Euclidean distance to the origin
within each |
labels |
A character vector of row names or integer indices
specifying which points to label. Overrides automatic |
label_size |
A numeric value specifying the font size of the
labels. Default: |
label_fg |
A character string specifying the text colour of the
labels. Default: |
label_bg |
A character string specifying the background colour of
the label boxes (passed to |
label_bg_r |
A numeric value specifying the corner radius of the
label background boxes (passed to |
highlight |
A character vector of row names or integer indices
specifying which points to highlight with an overlaid point layer in
|
highlight_color |
A character string specifying the colour of the
highlight points. Default: |
highlight_size |
A numeric value specifying the point size of the
highlight layer. Default: |
highlight_alpha |
A numeric value in |
highlight_stroke |
A numeric value specifying the stroke width of
the highlight point borders. Default: |
trim |
A numeric vector of length 2 specifying quantile bounds for
winsorizing the x-axis values. Values below the first quantile are
clamped to that quantile; values above the second quantile are clamped
to that quantile. Both values must be in |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
seed |
The random seed to use. Default is 8525. |
combine |
Logical; when |
ncol, nrow |
Integer number of columns / rows for the combined layout
(passed to |
byrow |
Logical; fill the combined layout by row. Default
|
axes |
A character string specifying how axes should be treated
across the combined layout (passed to
|
axis_titles |
A character string specifying how axis titles should
be treated across the combined layout. Defaults to |
guides |
A character string specifying how guides (legends) should
be collected across panels. Default |
design |
A custom layout design for the combined plot (passed to
|
... |
Additional arguments. |
Value
A ggplot object, a patchwork object, or a named
list of ggplot objects (when combine = FALSE), each with
height and width attributes in inches.
split_by Workflow
When split_by is provided:
The
split_bycolumn(s) are validated viacheck_columns()withforce_factor = TRUEandconcat_multi = TRUE(multiple columns are concatenated withsplit_by_sep).The data frame is split by
split_by(preserving factor level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
VolcanoPlotAtomic()is called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list.
Examples
set.seed(8525)
# Obtained by Seurat::FindMakers for the first cluster of pbmc_small
data <- data.frame(
avg_log2FC = c(
-3.69, -4.10, -2.68, -3.51, -3.09, -2.52, -3.53, -3.35, -2.82, -2.71, -3.16, -2.24,
-5.62, -3.10, -3.42, -2.72, -3.23, -3.25, -4.68, 3.67, -2.66, 4.79, -2.99, 10.14,
-1.78, -2.67, -2.26, -2.59, -3.39, 5.36, 4.56, 4.62, -2.94, -9.47, -9.12, -1.63,
-2.77, 3.31, -1.53, -3.89, -4.21, 4.72, -2.98, -2.29, -1.41, -9.48, -4.30, 3.01,
-1.19, -4.83, -1.35, -1.68, -1.63, -2.70, 3.86, 3.81, 7.23, -1.45, -0.92, -2.45,
3.91, -4.45, -9.33, 3.56, 2.27, -1.60, -1.15, 11.40, -9.77, -8.32, 2.61, -1.25,
-1.72, 10.61, 11.34, 10.02, 2.78, -3.48, -1.98, 5.86, 5.57, 4.57, 9.75, 9.97,
10.90, 9.19, 2.93, 5.10, -1.52, -3.93, -1.95, -2.46, -0.64, 4.60, -1.82, -0.80,
9.34, 7.51, 6.45, 5.23, 4.41, 3.60, -1.94, -1.15),
p_val_adj = c(
3.82e-09, 1.52e-07, 1.79e-07, 4.68e-07, 4.83e-07, 6.26e-07, 2.61e-06, 1.33e-05,
1.79e-05, 3.71e-05, 5.21e-05, 5.36e-05, 5.83e-05, 6.66e-05, 8.22e-05, 2.89e-04,
3.00e-04, 4.94e-04, 7.62e-04, 8.93e-04, 9.55e-04, 9.61e-04, 1.12e-03, 1.47e-03,
1.66e-03, 1.95e-03, 2.06e-03, 3.01e-03, 3.26e-03, 4.35e-03, 4.85e-03, 5.12e-03,
5.40e-03, 7.18e-03, 7.18e-03, 1.04e-02, 1.24e-02, 1.90e-02, 1.94e-02, 1.97e-02,
2.09e-02, 2.13e-02, 2.25e-02, 2.61e-02, 3.18e-02, 3.27e-02, 3.69e-02, 3.80e-02,
4.95e-02, 5.73e-02, 5.77e-02, 6.10e-02, 6.22e-02, 6.31e-02, 6.72e-02, 9.23e-02,
9.85e-02, 1.06e-01, 1.07e-01, 1.11e-01, 1.31e-01, 1.38e-01, 1.40e-01, 1.43e-01,
2.00e-01, 2.39e-01, 2.49e-01, 2.57e-01, 2.86e-01, 2.86e-01, 2.98e-01, 3.32e-01,
4.15e-01, 4.91e-01, 4.91e-01, 4.91e-01, 5.97e-01, 7.11e-01, 7.59e-01, 8.38e-01,
9.20e-01, 9.20e-01, 9.29e-01, 9.29e-01, 9.29e-01, 9.29e-01, 9.34e-01, 9.68e-01,
1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00,
1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00, 1.00e+00),
gene = c(
"HLA-DPB1", "LYZ", "HLA-DRA", "TYMP", "HLA-DPA1", "HLA-DRB1", "CST3", "HLA-DQB1",
"HLA-DRB5", "LST1", "HLA-DQA1", "AIF1", "S100A8", "IFITM3", "HLA-DMB", "FCGRT",
"SERPINA1", "IFI30", "S100A9", "CCL5", "GRN", "LCK", "HLA-DMA", "MS4A6A", "CTSS",
"CFP", "FCN1", "BID", "CFD", "CD3D", "CD7", "CD3E", "LGALS2", "CD14", "SMCO4",
"LINC00936", "HCK", "CTSW", "LGALS1", "HLA-DQA2", "LRRC25", "GZMM", "RNF130",
"LGALS3", "S100A11", "C5AR1", "IL1B", "GZMA", "FCER1G", "MPEG1", "TYROBP", "TSPO",
"GSTP1", "CTSB", "IL32", "CD247", "GNLY", "COTL1", "NFKBIA", "NUP214", "LAMP1",
"FPR1", "CLEC10A", "CST7", "PRF1", "BLVRA", "PSAP", "GZMH", "EAF2", "ASGR1",
"RARRES3", "SAT1", "LY86", "GP9", "TUBB1", "NGFRAP1", "XBP1", "SCO2", "RGS2", "GZMB",
"HIST1H2AC", "KLRD1", "PGRMC1", "AKR1C3", "PTGDR", "IL2RB", "GYPC", "CCL4", "CD68",
"FCER1A", "CD79B", "MS4A7", "CARD16", "ACAP1", "CD79A", "ANXA2", "TMEM40", "PF4",
"GNG11", "CLU", "CD9", "FGFBP2", "TNFRSF1B", "IFI6"),
pct_diff = c(
-0.752, -0.457, -0.460, -0.671, -0.626, -0.701, -0.502, -0.619, -0.623, -0.598,
-0.566, -0.626, -0.543, -0.566, -0.541, -0.542, -0.515, -0.489, -0.444, 0.428,
-0.517, 0.461, -0.491, -0.410, -0.480, -0.491, -0.521, -0.491, -0.438, 0.411,
0.411, 0.409, -0.438, -0.359, -0.359, -0.440, -0.386, 0.385, -0.332, -0.361, -0.361,
0.364, -0.387, -0.415, -0.454, -0.308, -0.335, 0.364, -0.454, -0.309, -0.379, -0.427,
-0.377, -0.389, 0.335, 0.315, 0.313, -0.284, -0.502, -0.309, 0.313, -0.284, -0.256,
0.309, 0.313, -0.364, -0.406, 0.244, -0.231, -0.231, 0.281, -0.311, -0.312, 0.220,
0.220, 0.220, 0.261, -0.232, -0.367, 0.240, 0.218, 0.218, 0.195, 0.195, 0.195, 0.195,
0.262, 0.218, -0.288, -0.207, -0.290, -0.233, -0.367, 0.217, -0.233, -0.403, 0.171,
0.194, 0.194, 0.194, 0.194, 0.213, -0.235, -0.292),
group = sample(LETTERS[1:2], 104, replace = TRUE)
)
# If set, it will be used as labels if label_by is not set.
# rownames(data) <- data$gene
# --- Basic usage ---
VolcanoPlot(data, x = "avg_log2FC", y = "p_val_adj", color_by = "pct_diff",
y_cutoff_name = "-log10(0.05)")
# --- With gene labels ---
VolcanoPlot(data, x = "avg_log2FC", y = "p_val_adj", color_by = "pct_diff",
y_cutoff_name = "-log10(0.05)", label_by = "gene")
# --- Mirrored layout ---
VolcanoPlot(data, x = "avg_log2FC", y = "p_val_adj", y_cutoff_name = "none",
flip_negatives = TRUE, label_by = "gene")
# --- With faceting ---
VolcanoPlot(data, x = "avg_log2FC", y = "p_val_adj", y_cutoff_name = "none",
flip_negatives = TRUE, facet_by = "group", label_by = "gene")
# --- With splitting ---
VolcanoPlot(data, x = "avg_log2FC", y = "p_val_adj", y_cutoff_name = "none",
flip_negatives = TRUE, split_by = "group", label_by = "gene")
# --- With highlighting ---
VolcanoPlot(data, x = "avg_log2FC", y = "p_val_adj", y_cutoff_name = "none",
highlight = c("ANXA2", "TMEM40", "PF4", "GNG11", "CLU", "CD9", "FGFBP2",
"TNFRSF1B", "IFI6"), label_by = "gene")
# --- Per-split palettes ---
VolcanoPlot(data, x = "avg_log2FC", y = "p_val_adj", color_by = "pct_diff",
y_cutoff_name = "-log10(0.05)", split_by = "group", label_by = "gene",
palette = c(A = "Set1", B = "Dark2"))
Atomic volcano plot (internal)
Description
Core implementation for drawing a single volcano plot. This is the
workhorse behind the exported VolcanoPlot function — it takes
a single data frame (no split_by support) and returns a
ggplot object. The plot displays statistical significance (typically
-log10 adjusted p-value) on the y-axis versus magnitude of change (log2
fold change) on the x-axis, with points coloured by significance category
or a user-supplied variable. Top features can be automatically labelled
via geom_text_repel(), and specific points can be
highlighted.
The function categorises points into three groups based on cutoff
thresholds: "sig_pos_x" (points exceeding both the positive
x-cutoff and y-cutoff), "sig_neg_x" (points exceeding both the
negative x-cutoff and y-cutoff), and "insig" (all remaining
points). When color_by = NULL, this categorisation drives point
colouring; otherwise the supplied column controls the colour scale.
Usage
VolcanoPlotAtomic(
data,
x,
y,
ytrans = function(n) -log10(n),
color_by = NULL,
color_name = NULL,
flip_negatives = FALSE,
x_cutoff = NULL,
y_cutoff = 0.05,
trim = c(0, 1),
xlim = NULL,
x_cutoff_name = NULL,
y_cutoff_name = NULL,
x_cutoff_color = "red2",
y_cutoff_color = "blue2",
x_cutoff_linetype = "dashed",
y_cutoff_linetype = "dashed",
x_cutoff_linewidth = 0.5,
y_cutoff_linewidth = 0.5,
pt_size = 2,
pt_alpha = 0.5,
nlabel = 5,
labels = NULL,
label_by = NULL,
label_size = 3,
label_fg = "black",
label_bg = "white",
label_bg_r = 0.1,
highlight = NULL,
highlight_color = "red",
highlight_size = 2,
highlight_alpha = 1,
highlight_stroke = 0.5,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
palreverse = FALSE,
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
seed = 8525,
...
)
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
ytrans |
A function to transform the y-axis values before plotting.
The default |
color_by |
A character string specifying the column name to colour
the points by. When |
color_name |
A character string for the colour legend title when
|
flip_negatives |
A logical value. When |
x_cutoff |
A numeric value specifying the x-axis significance
cutoff. Both the negative and positive of this value are used as
vertical threshold lines. When |
y_cutoff |
A numeric value specifying the y-axis significance
cutoff in the original (untransformed) scale. The value is
transformed by |
trim |
A numeric vector of length 2 specifying quantile bounds for
winsorizing the x-axis values. Values below the first quantile are
clamped to that quantile; values above the second quantile are clamped
to that quantile. Both values must be in |
xlim |
A numeric vector of length 2 to set the x-axis limits.
Passed to |
x_cutoff_name |
A character string for the x-cutoff legend entry.
When |
y_cutoff_name |
A character string for the y-cutoff legend entry.
When |
x_cutoff_color |
A character string specifying the colour of the
x-axis cutoff line(s). Default: |
y_cutoff_color |
A character string specifying the colour of the
y-axis cutoff line(s). Default: |
x_cutoff_linetype |
A character string specifying the linetype of
the x-axis cutoff line(s). Default: |
y_cutoff_linetype |
A character string specifying the linetype of
the y-axis cutoff line(s). Default: |
x_cutoff_linewidth |
A numeric value specifying the linewidth of
the x-axis cutoff line(s). Default: |
y_cutoff_linewidth |
A numeric value specifying the linewidth of
the y-axis cutoff line(s). Default: |
pt_size |
A numeric value specifying the point size for all data
points. Default: |
pt_alpha |
A numeric value in |
nlabel |
An integer specifying the number of top features to label
automatically. Points are ranked by Euclidean distance to the origin
within each |
labels |
A character vector of row names or integer indices
specifying which points to label. Overrides automatic |
label_by |
A character string specifying the column whose values
are used as label text. When |
label_size |
A numeric value specifying the font size of the
labels. Default: |
label_fg |
A character string specifying the text colour of the
labels. Default: |
label_bg |
A character string specifying the background colour of
the label boxes (passed to |
label_bg_r |
A numeric value specifying the corner radius of the
label background boxes (passed to |
highlight |
A character vector of row names or integer indices
specifying which points to highlight with an overlaid point layer in
|
highlight_color |
A character string specifying the colour of the
highlight points. Default: |
highlight_size |
A numeric value specifying the point size of the
highlight layer. Default: |
highlight_alpha |
A numeric value in |
highlight_stroke |
A numeric value specifying the stroke width of
the highlight point borders. Default: |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Input validation —
trim(must be length-2 in[0, 1]) andxlim(must be length-2 orNULL) are validated viastopifnot().trimis sorted. -
Column resolution —
x,y,color_by,facet_by, andlabel_byare validated and transformed viacheck_columns. Multi-columnfacet_byis concatenated withforce_factor = TRUE. -
y-axis transformation — the y-column is transformed by
ytrans()(default:-log10(n)). They_cutoffvalue is also transformed. -
x_cutoff defaulting — if
x_cutoffisNULL, it is set to0(suppressing the x-cutoff legend line). -
Category assignment — a
.categoryfactor with levelsc("sig_neg_x", "insig", "sig_pos_x")is created:When
y_cutoffis non-NULL: points with|x| > x_cutoffANDy > y_cutoffare significant.When
y_cutoffisNULL: only the x-cutoff determines significance.
-
Color resolution — three cases:
-
color_by = NULL: uses.categoryas a discrete colour column; the legend is suppressed. Character/factor column: discrete colour scale via
palette_this()andscale_color_manual(), guide suppressed.Numeric column: continuous gradient via
scale_color_gradientn()with a framed colour-bar legend.
-
-
Flip negatives — when
flip_negatives = TRUE, the y-values of points with negative x are multiplied by -1, creating a mirrored volcano where both up- and down-regulated features show their significance on the same side of the y-axis. -
Label column —
.labelis populated fromlabel_byorrownames(data). -
Trim / winsorize — x-values beyond the trim quantile bounds are clamped. When both bounds are nonzero and of opposite sign, they are symmetrised to the smaller absolute value. Outlying points are marked in
.outlier. -
Label selection — two modes:
Explicit
labels: the specified rows (by name or index) are marked for labelling.Automatic: top
nlabelpoints (by Euclidean distance to origin) are selected persign(x)group, and per facet level iffacet_byis set.
All labels are filtered to exclude
"insig"points. -
Data split — data is split into
pos_data(x >= 0) andneg_data(x < 0) so thatggrepellabels can nudge in opposite directions (positive points nudge left, negative points nudge right). -
Outlier jitter — outlier points are rendered separately with
position_jitter()to reduce overplotting. -
Base ggplot —
geom_point()layers for positive, negative, and outlier data, with colour mapped tocolor_by. -
Colour scale — discrete:
scale_color_manual()with"insig"forced to"grey"(whenpalcolorisNULL); continuous:scale_color_gradientn()with palette re-scaled so that the colour-bar is centred at 0. -
Highlight — when
highlightis provided, two additionalgeom_point()layers (non-outliers and outliers with jitter) overlay the highlighted points inhighlight_color. -
x-cutoff lines — vertical dashed lines at
+/- x_cutoffviageom_vline()withnew_scale_color(), labelled byx_cutoff_name. Suppressed whenx_cutoffisNULLor0. -
y-cutoff lines — horizontal dashed line(s) at
y_cutoff(or+/- y_cutoffwhenflip_negatives = TRUE) viageom_hline()withnew_scale_color(), labelled byy_cutoff_name. -
Flip-negatives axis — when
flip_negatives = TRUE, a solidgeom_hline(yintercept = 0)is added andscale_y_continuous(labels = abs)formats the y-axis. -
x-axis limits — optional
xlimpassed toggplot2::xlim(). -
Reference line and labels — a grey80 dashed vertical line at
x = 0, followed bygeom_text_repel()for positive and negative labelled points with separate x-nudges. -
Labels and theme —
labs(),coord_cartesian(clip = "off"),do_call(theme, theme_args), and theme elements foraspect.ratio,legend.position, andlegend.direction. -
Dimension calculation —
calculate_plot_dimensions()computesheightandwidthattributes frombase_height = 5,aspect.ratio, and legend geometry. -
Faceting —
facet_plot()wraps the plot withfacet_wrap/facet_gridiffacet_byis provided.
Word cloud plot
Description
Draws a word cloud plot that visualises word frequency and importance.
Words are displayed with font size proportional to a count variable and
colour based on a continuous score variable, using
geom_text_wordcloud for rendering.
The function supports pre-tokenised words (via word_by)
and sentence splitting (via sentence_by). Sentences are
automatically lowercased, stripped of punctuation, and split into
individual words before aggregation. Common stop words can be excluded
via words_excluded, and the number of displayed words is
controlled by top_words.
The word cloud can be faceted (via facet_by) or
split into separate sub-plots via split_by. When
split_by is used, each split level receives its own word cloud,
and the results are combined into a single layout via
combine_plots.
Usage
WordCloudPlot(
data,
word_by = NULL,
sentence_by = NULL,
count_by = NULL,
score_by = NULL,
count_name = NULL,
score_name = NULL,
split_by = NULL,
split_by_sep = "_",
words_excluded = plotthis::words_excluded,
score_agg = mean,
minchar = 2,
word_size = c(2, 8),
top_words = 100,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
alpha = 1,
palreverse = FALSE,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
seed = 8525,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
axes = NULL,
axis_titles = axes,
guides = NULL,
design = NULL,
...
)
Arguments
data |
A data frame. |
word_by |
A character string specifying the column name containing
pre-tokenized words. A character column is expected. Use this when your
data already has one word per row (or a list of words per row). Mutually
exclusive with |
sentence_by |
A character string specifying the column name containing
sentences or phrases to be split into individual words. A character column
is expected. The text is lowercased and punctuation is removed before
splitting on whitespace boundaries. Mutually exclusive with
|
count_by |
A character string specifying the numeric column for the
count or frequency of each word. When |
score_by |
A character string specifying the numeric column for the
score of each word, mapped to the text colour via a continuous gradient.
When |
count_name |
A character string for the size legend title. When
|
score_name |
A character string for the colour-bar legend title. When
|
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
words_excluded |
A character vector of words to exclude from the word
cloud. Matching is case-insensitive. Defaults to
|
score_agg |
A function to aggregate the scores when multiple
observations of the same word exist. Default is |
minchar |
A numeric value specifying the minimum number of characters
a word must have to be included. Words with fewer characters are filtered
out. Default: |
word_size |
A numeric vector of length 2 specifying the range of font
sizes (in mm) for the words. Passed to |
top_words |
A numeric value specifying the maximum number of words to
display, selected by highest score. Default: |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
seed |
The random seed to use. Default is 8525. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
... |
Additional arguments. |
Value
A ggplot object (when no split_by is used), a
patchwork object (when combine = TRUE and
split_by is used), or a named list of ggplot objects
(when combine = FALSE), each with height and
width attributes in inches.
split_by workflow
When split_by is provided:
-
validate_common_args()validates theseedandfacet_byconstraints (maximum 2 facet columns). The
themeargument is resolved viaprocess_theme().The
split_bycolumn(s) are validated and transformed viacheck_columns()withforce_factor = TRUEandconcat_multi = TRUE.The data frame is split by
split_by(preserving factor level order). Ifsplit_byisNULL, the data is wrapped in a single-element list with name"...".Per-split
palette,palcolor,legend.position, andlegend.directionare resolved viacheck_palette(),check_palcolor(), andcheck_legend().-
WordCloudPlotAtomic()is called for each split. Iftitleis a function, it receives the split level name and can generate dynamic titles per sub-plot. Results are combined via
combine_plots()(whencombine = TRUE) or returned as a named list (whencombine = FALSE).
Examples
set.seed(8525)
data <- data.frame(
word = c("apple", "banana", "cherry", "date", "elderberry",
"fig", "grape", "honeydew", "kiwi", "lemon"),
count = c(10, 20, 30, 40, 50, 15, 25, 35, 45, 55),
score = c(1, 2, 3, 4, 5, 1.5, 2.5, 3.5, 4.5, 5.5),
facet = rep(c("Group1", "Group2"), each = 5),
split = rep(c("A", "B"), 5)
)
# Basic word cloud with word, count, and score columns
WordCloudPlot(data, word_by = "word",
count_by = "count", score_by = "score")
# Word cloud using sentence_by (sentences split into words)
data_sent <- data.frame(
sentence = c("The quick brown fox jumps over the lazy dog",
"A quick brown dog jumps over a lazy fox"),
score = c(10, 5)
)
WordCloudPlot(data_sent, sentence_by = "sentence", score_by = "score")
# Word cloud with faceting
WordCloudPlot(data, word_by = "word",
count_by = "count", score_by = "score",
facet_by = "facet")
# Word cloud split by a grouping variable
WordCloudPlot(data, word_by = "word",
count_by = "count", score_by = "score",
split_by = "split")
Word cloud plot (internal)
Description
Core implementation for drawing a word cloud plot. This is the workhorse
behind the exported WordCloudPlot function — it takes a
single data frame (no split_by support) and returns a
ggplot object rendered via
geom_text_wordcloud.
The function supports two input modes:
-
Pre-tokenized words (
word_by) — each row contains a single word (or multiple words in a list column that is unnested). -
Sentence splitting (
sentence_by) — each row contains a sentence or phrase; the function splits the text into individual words after removing punctuation and lowercasing.
Words are displayed with font size proportional to a count
variable (count_by) and colour based on a continuous
score variable (score_by). Text filtering options allow removal of
short words, common stop words, and bracketed patterns.
Usage
WordCloudPlotAtomic(
data,
word_by = NULL,
sentence_by = NULL,
count_by = NULL,
score_by = NULL,
count_name = NULL,
score_name = NULL,
words_excluded = plotthis::words_excluded,
score_agg = mean,
minchar = 2,
word_size = c(2, 8),
top_words = 100,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
theme = "theme_this",
theme_args = list(),
palette = "Paired",
palcolor = NULL,
alpha = 1,
palreverse = FALSE,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
seed = 8525,
...
)
Arguments
data |
A data frame. |
word_by |
A character string specifying the column name containing
pre-tokenized words. A character column is expected. Use this when your
data already has one word per row (or a list of words per row). Mutually
exclusive with |
sentence_by |
A character string specifying the column name containing
sentences or phrases to be split into individual words. A character column
is expected. The text is lowercased and punctuation is removed before
splitting on whitespace boundaries. Mutually exclusive with
|
count_by |
A character string specifying the numeric column for the
count or frequency of each word. When |
score_by |
A character string specifying the numeric column for the
score of each word, mapped to the text colour via a continuous gradient.
When |
count_name |
A character string for the size legend title. When
|
score_name |
A character string for the colour-bar legend title. When
|
words_excluded |
A character vector of words to exclude from the word
cloud. Matching is case-insensitive. Defaults to
|
score_agg |
A function to aggregate the scores when multiple
observations of the same word exist. Default is |
minchar |
A numeric value specifying the minimum number of characters
a word must have to be included. Words with fewer characters are filtered
out. Default: |
word_size |
A numeric vector of length 2 specifying the range of font
sizes (in mm) for the words. Passed to |
top_words |
A numeric value specifying the maximum number of words to
display, selected by highest score. Default: |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
alpha |
A numeric value specifying the transparency of the plot. |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Value
A ggplot object with height and width
attributes (in inches) attached.
Architecture
-
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled"). -
Input validation — ensures exactly one of
word_byorsentence_byis specified. Errors if both are provided or neither is provided. Whensentence_byis used,count_bymust beNULL(counts are derived from occurrences after splitting). -
Column resolution —
facet_by,count_by, andscore_byare validated and transformed viacheck_columns. -
Default values — when
score_byisNULL, a synthetic.scorecolumn with value1is created. Whencount_byisNULL, a synthetic.countcolumn with value1is created. -
Sentence splitting branch (when
sentence_byis set):The
sentence_bycolumn is validated viacheck_columns.Text is lowercased, punctuation is removed, and the string is split into individual words on whitespace boundaries.
Words are unnested into separate rows via
unnest.Data is grouped by word (and
facet_bycolumns when present) and aggregated:sum(count_by)andscore_agg(score_by). Separate aggregation templates handle 0, 1, or 2facet_bycolumns.
-
Word branch (when
word_byis set):The
word_bycolumn is validated viacheck_columns.Column values are unnested into separate rows (supports list columns where a row may contain multiple words).
Data is grouped by word (and
facet_bycolumns when present) and aggregated similarly to the sentence branch.
-
Text filtering pipeline — the aggregated data is processed sequentially:
Words matching the pattern
[.*](bracketed content) are removed.Words with fewer than
mincharcharacters are removed.Words listed in
words_excludedare removed (case-insensitive matching).Duplicate rows are removed.
The top
top_wordswords by score are retained viaslice_max.
-
Angle assignment — each word is randomly assigned a rotation angle of 0 (60\ probability), creating the characteristic word cloud appearance.
-
Colour scale preparation —
palette_this()withtype = "continuous"generates a smooth gradient for thescorevariable. Acolors_valuesequence is created spanningmin(score)toquantile(score, 0.99)for colour interpolation. -
Plot assembly — the
ggplotobject is built with:-
ggwordcloud::geom_text_wordcloud()renders the words withrm_outside = TRUE, square shape, and eccentricity of 1. -
scale_color_gradientn()maps the score to the continuous colour gradient, with a colour-bar legend (titled byscore_nameor"Score"). -
scale_size()maps the count to font size within theword_sizerange, with a size legend (titled bycount_nameor"Count"). -
coord_flip()swaps the axes (word cloud convention). -
do_call(theme, theme_args)applies the selected theme;aspect.ratio,legend.position, andlegend.directionare set directly.
-
-
Dimension calculation —
calculate_plot_dimensions()computes plot height and width usingbase_height = 4.5,aspect.ratio, and legend metrics. The resultingheight/widthattributes are stored on theggplotobject. -
Faceting —
facet_plot()wraps the plot withfacet_wraporfacet_gridiffacet_byis provided, up to a maximum of 2 facet columns.
Convert a color with arbitrary transparency to a fixed color
Description
This function takes a vector of colors and an alpha level and converts the colors to fixed colors with the specified alpha level.
Usage
adjcolors(colors, alpha)
Arguments
colors |
Color vectors. |
alpha |
Alpha level ranging from 0 to 1. |
Value
The colors with the specified alpha level.
Adjust_network_layout
Description
Adjust_network_layout
Usage
adjust_network_layout(
graph,
layout,
width,
height = 2,
scale = 100,
iter = 100
)
Get a ggplot layer for background
Description
Get a ggplot layer for background
Usage
bg_layer(
data,
x,
keep_empty,
palette,
palcolor,
alpha,
facet_by,
direction = "vertical"
)
Arguments
data |
A data frame |
x |
A character string specifying the column name of the data frame to plot for the x-axis |
keep_empty |
A character string specifying whether to keep empty levels |
palette |
A character string specifying the palette to use |
palcolor |
A character string specifying the color to use in the palette |
alpha |
A numeric value specifying the transparency of the plot |
facet_by |
A character string specifying the column name(s) of the data frame to facet the plot |
direction |
A character string specifying the direction for the background |
Value
A ggplot layer for background
Blend colors
Description
This function blends a list of colors using the specified blend mode.
Usage
blend_colors(colors, mode = c("blend", "average", "screen", "multiply"))
Arguments
colors |
Color vectors. |
mode |
Blend mode. One of "blend", "average", "screen", or "multiply". |
Value
The blended color.
Blend a list of colors
Description
Blend a list of colors
Usage
blend_rgblist(Clist, mode = "blend", RGB_BackGround = c(1, 1, 1))
Blend two colors
Description
Blend two colors
Usage
blend_to_color(C1, C2, mode = "blend")
Calculate hjust and vjust based on angle
Description
Calculate hjust and vjust based on angle
Usage
calc_just(angle)
Arguments
angle |
A numeric value of the angle |
Value
A list with h and v values
Calculate plot dimensions with aspect ratio consideration
Description
This function calculates plot height and width taking into account:
Content-based scaling (number of items on axes)
Aspect ratio constraints
Legend position and direction
Minimum and maximum dimension bounds
Usage
calculate_plot_dimensions(
base_height = 4.5,
aspect.ratio = 1,
n_x = NULL,
n_y = NULL,
x_scale_factor = 0.5,
y_scale_factor = 0.5,
legend.position = "right",
legend.direction = "vertical",
legend_n = 1,
legend_nchar = 5,
flip = FALSE,
min_width = 3,
min_height = 3,
max_width = 12,
max_height = 12
)
Arguments
base_height |
Base height for the plot (before legend adjustments). Default is 4.5. |
aspect.ratio |
Aspect ratio (height/width). If NULL, width is calculated independently. |
n_x |
Number of categories on x-axis (for width scaling) |
n_y |
Number of categories on y-axis (for height scaling) |
x_scale_factor |
Scaling factor per x-axis category. Default is 0.5. |
y_scale_factor |
Scaling factor per y-axis category. Default is 0.5. |
legend.position |
Position of legend ("none", "right", "left", "top", "bottom") |
legend.direction |
Direction of legend ("vertical" or "horizontal") |
flip |
Whether the plot is flipped (inverts aspect ratio) |
min_width |
Minimum width in inches. Default is 3. |
min_height |
Minimum height in inches. Default is 3. |
max_width |
Maximum width in inches. Default is 12. |
max_height |
Maximum height in inches. Default is 12. |
Value
A list with height and width components
Check the columns if columns found in the data
Description
Check the columns if columns found in the data
Usage
check_columns(
df,
columns,
force_factor = FALSE,
allow_multi = FALSE,
concat_multi = FALSE,
concat_sep = "_"
)
Arguments
df |
A data frame |
columns |
A character vector of column names |
force_factor |
Whether to force the columns to be factors |
allow_multi |
Whether to allow multiple columns |
concat_multi |
Whether to concatenate multiple columns |
concat_sep |
The separator to use for concatenation |
Value
A character string of the valid column
check_keep_empty Check and normalize keep_empty parameter
Description
check_keep_empty Check and normalize keep_empty parameter
Usage
check_keep_empty(keep_empty, cols = NA)
Arguments
keep_empty |
keep_empty |
cols |
column names if keep_empty is a single value |
Value
normalized keep_empty
check_keep_na Check and normalize keep_na parameter
Description
check_keep_na Check and normalize keep_na parameter
Usage
check_keep_na(keep_na, cols = NA)
Arguments
keep_na |
keep_na |
cols |
column names if keep_na is a single value |
Value
normalized keep_na
check_legend Check if the legend.position and legend.direction are valid
Description
check_legend Check if the legend.position and legend.direction are valid
Usage
check_legend(
legend,
datas_name,
which = c("legend.position", "legend.direction")
)
Arguments
legend |
The value legend.position or legend.direction |
datas_name |
names of the split data |
Value
named list containing legend names
check_palcolor Check if the palcolor can be properly used
Description
check_palcolor Check if the palcolor can be properly used
Usage
check_palcolor(palcolor, datas_name)
Arguments
palcolor |
palcolor |
datas_name |
names of the split data |
Value
named list containing color names
check_palette Check if the palette can be properly used
Description
check_palette Check if the palette can be properly used
Usage
check_palette(palette, datas_name)
Arguments
palette |
palette |
datas_name |
names of the split data |
Value
named list containing palette names
Combine plots into one
Description
Combine plots into one
Usage
combine_plots(
plots,
combine = TRUE,
split_by = NULL,
nrow = NULL,
ncol = NULL,
byrow = NULL,
axes = NULL,
axis_titles = NULL,
guides = NULL,
design = NULL,
recalc_size = TRUE
)
Arguments
plots |
A list of plots |
combine |
Whether to combine the plots into one |
split_by |
The column name to split the plots by. When provided,
the combined data from all sub-plots is available via |
nrow |
The number of rows in the combined plot |
ncol |
The number of columns in the combined plot |
byrow |
Whether to fill the plots by row |
recalc_size |
Whether to re-calculate the size of the combined plot |
Value
The faceted plot. If guess_size is TRUE, attr(p, "height") and attr(p, "width") will be set
Common arguments for plots
Description
Common arguments for plots
Arguments
data |
A data frame. |
x |
A character string specifying the column name of the data frame to plot for the x-axis. |
y |
A character string specifying the column name of the data frame to plot for the y-axis. |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
palreverse |
A logical value indicating whether to reverse the palette. Default is FALSE. |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
alpha |
A numeric value specifying the transparency of the plot. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
axes |
A string specifying how axes should be treated. Passed to
|
axis_titles |
A string specifying how axis titltes should be treated. Passed to
|
guides |
A string specifying how guides should be treated in the layout. Passed to
|
design |
Specification of the location of areas in the layout, passed to |
seed |
The random seed to use. Default is 8525. |
... |
Additional arguments. |
Detect the type of the input data for an UpSet plot
Description
Inspects the structure of data and returns a classifier string that
downstream functions use to select the parsing strategy. When data
is an UpsetPlotData object (from prepare_upset_data())
it short-circuits to "upset" immediately.
Usage
detect_upset_datatype(data, group_by = NULL, id_by = NULL)
Arguments
data |
A data frame or a named list of element vectors. |
group_by |
A character string specifying the column name for the set-definition groups.
Only meaningful when |
id_by |
A character string specifying the column name for instance identifiers.
Required when |
Value
A character string, one of "long", "wide", "list",
or "upset".
"long"Long-format data — each row records one (set, element) pair.
"wide"Wide-format data — each row is an element and each set has its own logical/0-1 column.
"list"A named list of element vectors.
"upset"Already an
UpsetPlotDataobject.
Detect the input data format for Venn diagram processing
Description
Examines the structure of data and determines which of the four
supported formats it conforms to:
-
"long"— a data frame with one row per element-set pair. -
"wide"— a data frame with logical/0-1 columns per set. -
"list"— a named list of element vectors per set. -
"venn"— a pre-computedVennPlotDataobject.
Usage
detect_venn_datatype(data, group_by = NULL, id_by = NULL)
Arguments
data |
A data frame, a named list, or a |
group_by |
A character string specifying the column name(s) identifying
the set membership. A single non- |
id_by |
A character string specifying the column name that identifies
individual elements. Required when |
Value
A character string indicating the detected data format:
"long", "wide", "list", or "venn". Stops with
an error if the data does not match any recognised type.
An example data for dimensionality reduction plot
Description
This dataset is generated from the scvelo (scv.datasets.pancreas()) with the scvelo run on the dataset. Then the cell embeddings and velocity embeddings are extracted (200 downsampled), which are the first 4 columns of the data frame. The fifth column is the group identifier (clusters), and the sixth column is a fake grouping variable used to visualize stats, facetting, etc. An attribute "graph" is added to the data frame, which is a square matrix of the cell-cell distances, which is used for the graph (network) on dimensionality reduction plots.
Call a function with a list of arguments
Description
A faster alternative to do.call, especially when there are
large objects in the argument list. Named arguments are looked up by symbol
in the evaluation environment rather than being copied into the call, which
avoids the copying overhead of base::do.call. Unnamed arguments are
embedded in the call directly and do not benefit from this optimization.
Borrowed from Gmisc::fastDoCall.
Usage
do_call(what, args, quote = FALSE, envir = parent.frame())
Arguments
what |
either a function or a non-empty character string naming the function to be called. |
args |
a list of arguments to the function call. The
|
quote |
a logical value indicating whether to quote the arguments. |
envir |
an environment within which to evaluate the call. This
will be most useful if |
Value
The result of the function call
Theme element that add a box to the text
Description
Code grabbed from the ggtext package. See the original code at:
https://github.com/wilkelab/ggtext
This is used to create a text box around the text, primarily to be used in CorPairsPlot.
Usage
element_textbox(
family = NULL,
face = NULL,
size = NULL,
colour = NULL,
fill = NULL,
box.colour = NULL,
linetype = NULL,
linewidth = NULL,
hjust = NULL,
vjust = NULL,
halign = NULL,
valign = NULL,
lineheight = NULL,
margin = NULL,
padding = NULL,
width = NULL,
height = NULL,
minwidth = NULL,
maxwidth = NULL,
minheight = NULL,
maxheight = NULL,
r = NULL,
orientation = NULL,
color = NULL,
box.color = NULL,
debug = FALSE,
inherit.blank = FALSE
)
## S3 method for class 'element_textbox'
element_grob(
element,
label = "",
x = NULL,
y = NULL,
family = NULL,
face = NULL,
colour = NULL,
size = NULL,
hjust = NULL,
vjust = NULL,
lineheight = NULL,
margin = NULL,
...
)
Arguments
family |
Font family |
face |
Font face |
size |
Font size (in pt) |
colour, color |
Text color |
fill |
Fill color of the enclosing box |
box.colour, box.color |
Line color of the enclosing box (if different from the text color) |
linetype |
Line type of the enclosing box (like |
linewidth |
Line width of the enclosing box (measured in mm, just like |
hjust |
Horizontal justification |
vjust |
Vertical justification |
halign |
Horizontal justification |
valign |
Vertical justification |
lineheight |
Line height, in multiples of the font size |
padding, margin |
Padding and margins around the text box.
See |
width, height |
Unit objects specifying the width and height
of the textbox, as in |
minwidth, minheight, maxwidth, maxheight |
Min and max values for width and height. Set to NULL to impose neither a minimum nor a maximum. |
r |
Unit value specifying the corner radius of the box |
orientation |
Orientation of the text box. See |
debug |
Not implemented. |
inherit.blank |
See |
element |
A theme element created by |
label |
Text to display in the textbox. |
x, y |
Position of the textbox. |
... |
Other arguments passed to |
Value
A ggplot2 theme element that can be used inside a ggplot2::theme() call.
An example of clusterProfiler enrichment result
Description
An example of clusterProfiler enrichment result
Examples
## Not run:
if (interactive()) {
data(geneList, package="DOSE")
de <- names(geneList)[abs(geneList) > 1.5]
enrich_example <- clusterProfiler::enrichPathway(gene=de, pvalueCutoff = 0.05, readable=TRUE)
enrich_example <- as.data.frame(enrich_example)
}
## End(Not run)
An example of clusterProfiler enrichment result with multiple databases
Description
An example of clusterProfiler enrichment result with multiple databases
Examples
## Not run:
if (interactive()) {
data(enrich_example, package="plotthis")
enrich_example$Database <- "DB1"
enrich_example2 <- enrich_example
enrich_example2$Database <- "DB2"
enrich_example2$ID <- paste0(enrich_example2$ID, "_DB2")
enrich_example2$Description <- paste0(enrich_example2$Description, " (DB2)")
enrich_multidb_example <- rbind(enrich_example, enrich_example2)
}
## End(Not run)
Facetting a plot
Description
Facetting a plot
Usage
facet_plot(
plot,
facet_by,
facet_scales,
nrow,
ncol,
byrow,
legend.position = "right",
legend.direction = "vertical",
recalc_size = TRUE,
...
)
Arguments
plot |
The plot to facet or a list list(plot, height, width) if guess_size is TRUE |
facet_by |
The column(s) to split data by and plot separately or facet by If NULL, no faceting will be done |
facet_scales |
Whether to scale the axes of facets. |
nrow |
The number of rows in facet_wrap |
ncol |
The number of columns in facet_wrap |
byrow |
Whether to fill the plots by row |
legend.position |
The position of the legend |
legend.direction |
The direction of the legend |
recalc_size |
Whether to re-calculate the size of the plot |
... |
Additional arguments to pass to facet_wrap or facet_grid |
Value
The faceted plot. If guess_size is TRUE, attr(p, "height") and attr(p, "width") will be set
Prepare cutoff data for ROC curve annotation
Description
Internal helper that computes the sensitivity and specificity values for a
set of user-supplied cutoff points (or computed via OptimalCutpoints methods)
across categories defined by group_by and/or facet_by columns. Used by
ROCCurveAtomic() to annotate the ROC curve with cutoff markers and labels.
Usage
get_cutoffs_data(
data,
truth_by,
score_by,
cat_by,
cutoffs_at = NULL,
cutoffs_labels = NULL,
cutoffs_accuracy = 0.001,
n_cuts = 0,
increasing = TRUE
)
Arguments
data |
A data frame with the truth and score columns. |
truth_by |
A character string of the column name that contains the true class labels (binary, 0/1 or TRUE/FALSE). |
score_by |
A character string of the column name that contains the predicted scores. |
cat_by |
A character string of the column name to categorise/group the data. When specified, cutoffs are calculated separately for each category level, enabling per-group or per-facet cutoff annotation. |
cutoffs_at |
A vector of user-supplied cutoff values to plot as points.
When non-NULL, overrides |
cutoffs_labels |
A character vector of user-supplied labels for the
cutoffs. Must be the same length as |
cutoffs_accuracy |
A numeric value specifying the rounding precision
for automatically generated cutoff labels. Default: |
n_cuts |
An integer specifying the number of evenly-spaced quantile-based
cutoff points. Ignored when |
increasing |
A logical value. If TRUE (default), higher scores indicate the positive class; if FALSE, lower scores indicate the positive class. |
Details
Cutoffs can be specified either as numeric values (raw score thresholds) or as
method names from the OptimalCutpoints package for automatic optimal
cutoff identification. When n_cuts > 0, n_cuts evenly-spaced
quantile values of the score distribution are used as cutoffs.
Value
A data frame with columns cutoff, x (1 - specificity),
y (sensitivity), label, and cat_by (the category name).
An example of GSEA result from fgsea package
Description
An example of GSEA result from fgsea package
Examples
## Not run:
if (interactive()) {
set.seed(1234)
data(geneList, package="DOSE")
gsea_example <- DOSE::gseDO(geneList)
gene_ranks <- gsea_example@geneList
gene_sets <- gsea_example@geneSets
gsea_example_pos <- gsea_example[gsea_example$p.adjust < 0.05 & gsea_example$NES > 0, ]
gsea_example_neg <- gsea_example[gsea_example$p.adjust < 0.05 & gsea_example$NES < 0, ]
gsea_example <- rbind(
gsea_example_pos[sample(1:nrow(gsea_example_pos), 5), ],
gsea_example_pos[sample(1:nrow(gsea_example_pos), 5), ]
)
attr(gsea_example, "gene_ranks") <- gene_ranks
attr(gsea_example, "gene_sets") <- gene_sets[gsea_example$ID]
}
## End(Not run)
Get the running enrichment score of a gene set
Description
Get the running enrichment score of a gene set
Usage
gsea_running_score(genes, gene_ranks, exponent = 1, hits_only = TRUE)
Arguments
genes |
A vector of genes |
gene_ranks |
A numeric vector of gene ranks with names |
exponent |
A numeric value to raise the gene ranks to |
hits_only |
A logical value to return only the running enrichment score of the hits |
Value
A numeric vector of the running enrichment score
Join the meta data to the main data frame for heatmap
Description
Join the meta data to the main data frame for heatmap
Usage
join_heatmap_meta(data, meta_data, by, cr_split_by, split_by, which)
Arguments
data |
A data frame containing the main data for the heatmap. |
meta_data |
A data frame containing the meta data to be joined. |
by |
A character string specifying the column name in |
cr_split_by |
A character string specifying the column name in |
split_by |
A character string specifying the column name in |
which |
A character string specifying whether to join on rows or columns.
Can be either |
Value
A data frame with the meta data joined to the main data.
Heatmap layer functions used to draw on the heatmap cells
Description
Heatmap layer functions used to draw on the heatmap cells
Usage
layer_white_bg(j, i, x, y, w, h, fill)
layer_bg(j, i, x, y, w, h, fill, alpha)
layer_reticle(j, i, x, y, w, h, fill, color)
layer_dot(
j,
i,
x,
y,
w,
h,
fill,
data,
dot_size,
alpha,
row_names = NULL,
col_names = NULL
)
layer_bars(j, i, x, y, w, h, fill, flip, col_fun, data, alpha)
layer_pie(j, i, x, y, w, h, fill, palette, palcolor, data, pie_size)
layer_boxviolin(j, i, x, y, w, h, fill, flip, data, colors, fn)
Arguments
j |
An integer specifying the column index |
i |
An integer specifying the row index |
x |
A numeric vector specifying the x position |
y |
A numeric vector specifying the y position |
w |
A numeric vector specifying the width |
h |
A numeric vector specifying the height |
fill |
A character vector specifying the fill color |
alpha |
A numeric value between 0 and 1 specifying the transparency of the fill color |
color |
A character vector specifying the color of the reticle |
data |
A dataframe used to create the annotation. Different from the data used to create the heatmap itself, which is aggregated data. This dataframe is the original data, where each cell could have multiple values. |
dot_size |
A numeric value specifying the size of the dot or a function to calculate the size from the values in the cell. The function can take 1, 3, or 5 arguments: the first argument is the values in the cell before aggregation; the 2nd and 3rd arguments are the row and column indices; the 4th and 5th arguments are the row and column names. |
row_names |
Row names from the heatmap matrix. |
col_names |
Column names from the heatmap matrix. |
col_fun |
A function to calculate the color of the bars |
colors |
A character vector specifying the fill color of the violin plot. If not provided, the fill color of row/column annotation will be used |
Expand the plot area with CSS-like padding
Description
Expand the plot area with CSS-like padding
Usage
norm_expansion(
expand,
x_type,
y_type,
continuous_default = c(0.05, 0),
discrete_default = c(0, 0.6)
)
Arguments
expand |
A numeric vector of length 1, 2, 3, or 4 The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
x_type |
The type of x-axis, either "continuous" or "discrete" |
y_type |
The type of y-axis, either "continuous" or "discrete" |
Value
A list with x and y values for expand
A list of palettes for use in data visualization
Description
A list of palettes for use in data visualization
Examples
## Not run:
if (interactive()) {
library(stringr)
library(RColorBrewer)
library(Redmonder)
library(rcartocolor)
library(nord)
library(viridis)
library(pals)
library(dichromat)
library(jcolors)
library(scales)
library(ggthemes)
syspals <- utils::getFromNamespace("syspals", "pals")
brewer.pal.info <- RColorBrewer::brewer.pal.info
ggsci_db <- utils::getFromNamespace("ggsci_db", "ggsci")
redmonder.pal.info <- Redmonder::redmonder.pal.info
metacartocolors <- rcartocolor::metacartocolors
rownames(metacartocolors) <- metacartocolors$Name
nord_palettes <- nord::nord_palettes
viridis_names <- c("magma", "inferno", "plasma", "viridis", "cividis", "rocket",
"mako", "turbo")
viridis_palettes <- lapply(stats::setNames(viridis_names, viridis_names),
function(x) viridis::viridis(100, option = x))
ocean_names <- names(syspals)[grep("ocean", names(syspals))]
ocean_palettes <- syspals[ocean_names]
dichromat_palettes <- dichromat::colorschemes
jcolors_names <- paste0("jcolors-", c("default", "pal2", "pal3", "pal4", "pal5",
"pal6", "pal7", "pal8", "pal9", "pal10", "pal11", "pal12", "rainbow"))
custom_names <- c("jet", "simspec", "GdRd")
custom_palettes <- list(
oompaBase::jetColors(N = 100),
c("#c22b86", "#f769a1", "#fcc5c1", "#253777", "#1d92c0", "#9ec9e1", "#015b33",
"#42aa5e", "#d9f0a2", "#E66F00", "#f18c28", "#FFBB61"),
c("gold", "red3")
)
names(custom_palettes) <- custom_names
seurat_discrete_palettes <- list(
alphabet = c(
"#F0A0FF", "#0075DC", "#993F00", "#4C005C", "#191919", "#005C31",
"#2BCE48", "#FFCC99", "#808080", "#94FFB5", "#8F7C00", "#9DCC00",
"#C20088", "#003380", "#FFA405", "#FFA8BB", "#426600", "#FF0010",
"#5EF1F2", "#00998F", "#E0FF66", "#740AFF", "#990000", "#FFFF80",
"#FFE100", "#FF5005"
),
alphabet2 = c(
"#AA0DFE", "#3283FE", "#85660D", "#782AB6", "#565656", "#1C8356",
"#16FF32", "#F7E1A0", "#E2E2E2", "#1CBE4F", "#C4451C", "#DEA0FD",
"#FE00FA", "#325A9B", "#FEAF16", "#F8A19F", "#90AD1C", "#F6222E",
"#1CFFCE", "#2ED9FF", "#B10DA1", "#C075A6", "#FC1CBF", "#B00068",
"#FBE426", "#FA0087"
),
glasbey = c(
"#0000FF", "#FF0000", "#00FF00", "#000033", "#FF00B6", "#005300",
"#FFD300", "#009FFF", "#9A4D42", "#00FFBE", "#783FC1", "#1F9698",
"#FFACFD", "#B1CC71", "#F1085C", "#FE8F42", "#DD00FF", "#201A01",
"#720055", "#766C95", "#02AD24", "#C8FF00", "#886C00", "#FFB79F",
"#858567", "#A10300", "#14F9FF", "#00479E", "#DC5E93", "#93D4FF",
"#004CFF", "#F2F318"
),
polychrome = c(
"#5A5156", "#E4E1E3", "#F6222E", "#FE00FA", "#16FF32", "#3283FE",
"#FEAF16", "#B00068", "#1CFFCE", "#90AD1C", "#2ED9FF", "#DEA0FD",
"#AA0DFE", "#F8A19F", "#325A9B", "#C4451C", "#1C8356", "#85660D",
"#B10DA1", "#FBE426", "#1CBE4F", "#FA0087", "#FC1CBF", "#F7E1A0",
"#C075A6", "#782AB6", "#AAF400", "#BDCDFF", "#822E1C", "#B5EFB5",
"#7ED7D1", "#1C7F93", "#D85FF7", "#683B79", "#66B0FF", "#3B00FB"
),
stepped = c(
"#990F26", "#B33E52", "#CC7A88", "#E6B8BF", "#99600F", "#B3823E",
"#CCAA7A", "#E6D2B8", "#54990F", "#78B33E", "#A3CC7A", "#CFE6B8",
"#0F8299", "#3E9FB3", "#7ABECC", "#B8DEE6", "#3D0F99", "#653EB3",
"#967ACC", "#C7B8E6", "#333333", "#666666", "#999999", "#CCCCCC"
),
parade = c(
'#ff6969', '#9b37ff', '#cd3737', '#69cdff', '#ffff69', '#69cdcd',
'#9b379b', '#3737cd', '#ffff9b', '#cdff69', '#ff9b37', '#37ffff',
'#9b69ff', '#37cd69', '#ff3769', '#ff3737', '#37ff9b', '#cdcd37',
'#3769cd', '#37cdff', '#9b3737', '#ff699b', '#9b9bff', '#cd9b37',
'#69ff37', '#cd3769', '#cd69cd', '#cd6937', '#3737ff', '#cdcd69',
'#ff9b69', '#cd37cd', '#9bff37', '#cd379b', '#cd6969', '#69ff9b',
'#ff379b', '#9bff9b', '#6937ff', '#69cd37', '#cdff37', '#9bff69',
'#9b37cd', '#ff37ff', '#ff37cd', '#ffff37', '#37cd9b', '#379bff',
'#ffcd37', '#379b37', '#ff9bff', '#379b9b', '#69ffcd', '#379bcd',
'#ff69ff', '#ff9b9b', '#37ff69', '#ff6937', '#6969ff', '#699bff',
'#ffcd69', '#69ffff', '#37ff37', '#6937cd', '#37cd37', '#3769ff',
'#cd69ff', '#6969cd', '#9bcd37', '#69ff69', '#37cdcd', '#cd37ff',
'#37379b', '#37ffcd', '#69cd69', '#ff69cd', '#9bffff', '#9b9b37'
)
)
seurat_continuous_palettes <- list(
seurat = hue_pal()(16),
seurat.16 = hue_pal()(16),
seurat.32 = hue_pal()(32),
seurat.64 = hue_pal()(64)
)
stripe_palettes <- list(
stripe = rep(c("white", "grey60"), 8),
stripe.16 = rep(c("white", "grey60"), 8),
stripe.32 = rep(c("white", "grey60"), 16),
stripe.64 = rep(c("white", "grey60"), 32)
)
tableau_palettes <- list()
orig_tableau_palettes <- ggthemes::ggthemes_data[["tableau"]][["color-palettes"]]
for (g in names(orig_tableau_palettes)) {
for (pal in names(orig_tableau_palettes[[g]])) {
palcolors <- as.list(orig_tableau_palettes[[g]][[pal]])
if (!is.null(palcolors$name)) {
tableau_palettes[[pal]] <- stats::setNames(palcolors$value, palcolors$name)
} else {
tableau_palettes[[pal]] <- palcolors$value
}
}
}
palette_list <- list()
all_colors <- c(
rownames(brewer.pal.info), names(ggsci_db), rownames(redmonder.pal.info),
rownames(metacartocolors), names(nord_palettes), names(viridis_palettes),
ocean_names, names(dichromat_palettes), jcolors_names, names(seurat_discrete_palettes),
names(seurat_continuous_palettes), custom_names, names(stripe_palettes),
names(tableau_palettes)
)
for (pal in all_colors) {
if (!pal %in% all_colors) {
stop(paste0("Invalid pal Must be one of ", paste0(all_colors, collapse = ",")))
}
if (pal %in% rownames(brewer.pal.info)) {
pal_n <- brewer.pal.info[pal, "maxcolors"]
pal_category <- brewer.pal.info[pal, "category"]
if (pal_category == "div") {
palcolor <- rev(brewer.pal(name = pal, n = pal_n))
} else {
if (pal == "Paired") {
palcolor <- brewer.pal(12, "Paired")[c(1:4, 7, 8, 5, 6, 9, 10, 11, 12)]
} else {
palcolor <- brewer.pal(name = pal, n = pal_n)
}
}
if (pal_category == "qual") {
attr(palcolor, "type") <- "discrete"
} else {
attr(palcolor, "type") <- "continuous"
}
} else if (pal %in% names(ggsci_db)) {
if (pal %in% c("d3", "uchicago", "material")) {
for (subpal in names(ggsci_db[[pal]])) {
palcolor <- ggsci_db[[pal]][[subpal]]
if (pal == "material") {
attr(palcolor, "type") <- "continuous"
} else {
attr(palcolor, "type") <- "discrete"
}
palette_list[[paste0(pal, "-", subpal)]] <- palcolor
}
next
} else {
palcolor <- ggsci_db[[pal]][[1]]
if (pal == "gsea") {
attr(palcolor, "type") <- "continuous"
} else {
attr(palcolor, "type") <- "discrete"
}
}
} else if (pal %in% rownames(redmonder.pal.info)) {
pal_n <- redmonder.pal.info[pal, "maxcolors"]
pal_category <- redmonder.pal.info[pal, "category"]
if (pal_category == "div") {
palcolor <- rev(redmonder.pal(name = pal, n = pal_n))
} else {
palcolor <- redmonder.pal(name = pal, n = pal_n)
}
if (pal_category == "qual") {
attr(palcolor, "type") <- "discrete"
} else {
attr(palcolor, "type") <- "continuous"
}
} else if (pal %in% rownames(metacartocolors)) {
pal_n <- metacartocolors[pal, "Max_n"]
palcolor <- carto_pal(name = pal, n = pal_n)
if (pal_category == "qualitative") {
attr(palcolor, "type") <- "discrete"
} else {
attr(palcolor, "type") <- "continuous"
}
} else if (pal %in% names(nord_palettes)) {
palcolor <- nord_palettes[[pal]]
attr(palcolor, "type") <- "discrete"
} else if (pal %in% names(viridis_palettes)) {
palcolor <- viridis_palettes[[pal]]
attr(palcolor, "type") <- "continuous"
} else if (pal %in% names(ocean_palettes)) {
palcolor <- ocean_palettes[[pal]]
attr(palcolor, "type") <- "continuous"
} else if (pal %in% names(dichromat_palettes)) {
palcolor <- dichromat_palettes[[pal]]
if (pal %in% c("Categorical.12", "SteppedSequential.5")) {
attr(palcolor, "type") <- "discrete"
} else {
attr(palcolor, "type") <- "continuous"
}
} else if (pal %in% jcolors_names) {
palcolor <- jcolors(palette = gsub("jcolors-", "", pal))
if (pal %in% paste0("jcolors-", c("pal10", "pal11", "pal12", "rainbow"))) {
attr(palcolor, "type") <- "continuous"
} else {
attr(palcolor, "type") <- "discrete"
}
} else if (pal %in% custom_names) {
palcolor <- custom_palettes[[pal]]
if (pal %in% c("jet")) {
attr(palcolor, "type") <- "continuous"
} else {
attr(palcolor, "type") <- "discrete"
}
} else if (pal %in% names(seurat_discrete_palettes)) {
palcolor <- seurat_discrete_palettes[[pal]]
attr(palcolor, "type") <- "discrete"
} else if (pal %in% names(seurat_continuous_palettes)) {
palcolor <- seurat_continuous_palettes[[pal]]
attr(palcolor, "type") <- "continuous"
} else if (pal %in% names(stripe_palettes)) {
palcolor <- stripe_palettes[[pal]]
attr(palcolor, "type") <- "discrete"
} else if (pal %in% names(tableau_palettes)) {
palcolor <- tableau_palettes[[pal]]
attr(palcolor, "type") <- "discrete"
}
palette_list[[pal]] <- palcolor
}
}
## End(Not run)
Color palettes collected in plotthis.
Description
Color palettes collected in plotthis.
Usage
palette_this(
x,
n = 100,
palette = "Paired",
palcolor = NULL,
type = "auto",
keep_names = TRUE,
alpha = 1,
matched = FALSE,
reverse = FALSE,
NA_keep = FALSE,
NA_color = "grey80",
transparent = TRUE
)
Arguments
x |
A vector of character/factor or numeric values. If missing, numeric values 1:n will be used as x. |
n |
The number of colors to return for numeric values. |
palette |
Palette name. All available palette names can be queried with |
palcolor |
Custom colors used to create a color palette. |
type |
Type of |
keep_names |
Whether to keep the names of the color vector. |
alpha |
The alpha value of the colors. Default is 1. |
matched |
If |
reverse |
Whether to invert the colors. |
NA_keep |
Whether to keep the color assignment to NA in |
NA_color |
Color assigned to NA if NA_keep is |
transparent |
Whether to make the colors transparent when alpha < 1.
When |
Value
A vector of colors.
Prepare continuous color scale limits with quantile/cutoff controls
Description
Computes the lower and upper cutoffs for a continuous color/fill scale,
applies data winsorization (clamping), and returns the results needed
by scale_fill_gradientn or
scale_color_gradientn.
Usage
prepare_continuous_color_scale(
data,
column,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
bg_cutoff = NULL
)
Arguments
data |
A data frame. |
column |
The column name in |
lower_quantile, upper_quantile |
Lower and upper quantiles for the continuous color/fill scale.
The actual cutoffs are determined by these quantiles when |
lower_cutoff, upper_cutoff |
Explicit lower and upper cutoffs for the continuous color/fill scale.
When |
bg_cutoff |
Optional numeric cutoff — values |
Value
A list with components:
data |
The modified data frame (with winsorized |
feat_colors_value |
Numeric vector of 100 evenly-spaced values from
|
limits |
Numeric vector of length 2 giving the range
|
Process the enrichment results from Enrichr
Description
Process the enrichment results from Enrichr
Usage
prepare_enrichr_result(data, dbname = "Database", n_input = NULL)
Arguments
data |
A data frame containing the result by Enrichr. |
dbname |
A character string specifying the name of the database column. |
n_input |
An integer specifying the number of input genes. Enrichr result doesn't ship with the number of input genes. You can either provide the number directly or we will infer it. See details. |
Details
In order to use the EnrichMap and EnrichNetwork functions and other visualization functions in plotthis,
the enrichment results from Enrichr need to be processed by the prepare_enrichr_result function.
The following columns are renamed:
-
Term->Description -
Genes->geneID(separated replaced by/) -
P.value->pvalue -
Adjusted.P.value->p.adjustAdditionally, GeneRatio and BgRatio columns are inferred. From enrichr's documentation, the oddsRatio is defined as:oddsRatio = (A * (D - B - C + A) / max((B - A) * (C - A), 1), where A is the overlapping genes; B is the total genes in the gene set; C (n_input) is the genes in input list; D is the total genes in the background. D is not provided by Enrichr. To infer it,D = oddsRatio * max((B - A) * (C - A), 1) / A + B + C - A. -
Overlap = A / B(from Enrichr) -
GeneRatio = A / C(from ClusterProfiler) -
BgRatio = B / D(from ClusterProfiler)C (n_input), if not provided, will be inferred whenDfor all terms are equal. When starting inferrence, the minimum value to try will be unique genes indata$Genes/data$geneID.
Value
A data frame that can be used in EnrichMap.
Prepare fgsea result for plotting
Description
Prepare fgsea result for plotting
Usage
prepare_fgsea_result(data)
Arguments
data |
A data frame of fgsea results |
Value
A data frame with the desired columns for plotting and the gene ranks and gene sets as attributes
Prepare data for an UpSet plot
Description
Converts raw input (long data frame, wide data frame, named list, or an
existing UpsetPlotData object) into the internal format expected by
UpsetPlotAtomic(). This is the data-preparation workhorse
that handles all input format parsing.
Usage
prepare_upset_data(
data,
in_form = "auto",
group_by = NULL,
group_by_sep = "_",
id_by = NULL,
specific = TRUE
)
Arguments
data |
A data frame, a named list of element vectors, or an
|
in_form |
A character string specifying the input format. One of
|
group_by |
A character vector of column name(s) defining the sets.
In long format, this is the column with set labels. In wide format,
these are the set-membership columns. When |
group_by_sep |
A character string to concatenate multiple
|
id_by |
A character string specifying the column name for instance
identifiers. Required for long format; optional for wide format (a
synthetic |
specific |
A logical value. When |
Value
An UpsetPlotData object — a data frame with an
Intersection list-column of set labels and one row per element.
A "group_order" attribute preserves the original set order.
Input formats
Long format — one row per (set, element) pair:
group_by id_by A a1 A a2 B a1 B a3
Requires both group_by and id_by.
Wide format — each row is an element, each set has a logical or 0/1 membership column:
A B TRUE TRUE TRUE FALSE FALSE TRUE
The set columns are identified by group_by (or all columns except
id_by when group_by = NULL).
List format — a named list of element vectors:
list(A = c("a1", "a2"), B = c("a1", "a3"))
UpsetPlotData — a pre-processed object (returned by this function)
is returned unchanged (with a warning if group_by is also provided).
Prepare input data for Venn diagram rendering
Description
Converts data in any supported input format into a VennPlotData
object suitable for rendering by ggVennDiagram. When
in_form = "auto" (the default), the format is detected via
detect_venn_datatype().
Usage
prepare_venn_data(
data,
in_form = "auto",
group_by = NULL,
group_by_sep = "_",
id_by = NULL
)
Arguments
data |
A data frame, a named list, or a |
in_form |
A character string specifying the input format. One of
|
group_by |
A character string (or vector) specifying the column name(s)
identifying set membership. For long-format data, a single column defines
the set; multiple columns are concatenated with |
group_by_sep |
A character string used to concatenate multiple
|
id_by |
A character string specifying the column name that identifies individual elements. Required for long-format data; ignored otherwise. |
Value
A VennPlotData object suitable for rendering by
ggVennDiagram.
Input formats
-
Long format — a data frame with a grouping column (
group_by) identifying the set and an ID column (id_by) identifying each element. Multiplegroup_bycolumns are concatenated withgroup_by_sep.group_by id_by A a1 A a2 B a1 B a3
-
Wide format — a data frame where each column represents a set and each row an element. Values must be logical or
0/1. Columns specified ingroup_bydefine the sets; ifgroup_byisNULL, all columns are used.A B TRUE TRUE TRUE FALSE FALSE TRUE
-
List format — a named list where each element is a vector of identifiers belonging to that set.
list(A = c("a1", "a2"), B = c("a1", "a3")) -
VennPlotData — a pre-computed object returned by a previous call to
prepare_venn_data(). Returned as-is.
Process/normalize data passed to Heatmap()
Description
This function is used to process the data passed to Heatmap().
Usage
process_heatmap_data(
data,
in_form,
values_by,
name,
split_by,
split_by_sep,
rows_orderby,
columns_orderby,
rows_by,
rows_by_sep,
rows_name,
rows_split_by,
rows_split_by_sep,
rows_split_name,
columns_by,
columns_by_sep,
columns_name,
columns_split_by,
columns_split_by_sep,
columns_split_name,
pie_group_by,
pie_group_by_sep,
pie_name,
rows_data,
columns_data,
keep_na,
keep_empty
)
Arguments
data |
A data frame or matrix containing the data to be plotted.
Based on the
|
in_form |
The format of the data. Can be one of |
values_by |
A character of column name in |
name |
A character string to name the heatmap (will be used to rename |
split_by |
A character of column name in |
split_by_sep |
A character string to concat multiple columns in |
rows_orderby |
A expression (in character) to specify how to order rows. It will be evaluated in the context of the data frame used for rows (after grouping by rows_split_by and rows_by). The expression should return a vector of the same length as the number of rows in the data frame. The default is NULL, which means no specific ordering. Can't be used with cluster_rows = TRUE. This is applied before renaming rows_by to rows_name. |
columns_orderby |
A expression (in character) to specify how to order columns. It will be evaluated in the context of the data frame used for columns (after grouping by columns split_by and columns_by). The expression should return a vector of the same length as the number of rows in the data frame. The default is NULL, which means no specific ordering. Can't be used with cluster_columns = TRUE. This is applied before renaming columns_by to columns_name. |
rows_by |
A vector of column names in |
rows_by_sep |
A character string to concat multiple columns in |
rows_name |
A character string to rename the column created by |
rows_split_by |
A character of column name in |
rows_split_by_sep |
A character string to concat multiple columns in |
rows_split_name |
A character string to rename the column created by |
columns_by |
A vector of column names in |
columns_by_sep |
A character string to concat multiple columns in |
columns_name |
A character string to rename the column created by |
columns_split_by |
A character of column name in |
columns_split_by_sep |
A character string to concat multiple columns in |
columns_split_name |
A character string to rename the column created by |
pie_group_by |
A character of column name in |
pie_group_by_sep |
A character string to concat multiple columns in |
pie_name |
A character string to rename the column created by |
rows_data |
A data frame containing additional data for rows, which can be used to add annotations to the heatmap.
It will be joined to the main data by |
columns_data |
A data frame containing additional data for columns, which can be used to add annotations to the heatmap.
It will be joined to the main data by |
keep_na |
Whether we should keep NA groups in rows, columns and split_by variables. Default is FALSE. FALSE to remove NA groups; TRUE to keep NA groups. A vector of column names can also be provided to specify which columns to keep NA groups. Note that the record will be removed if any of the grouping columns has NA and is not specified to keep NA. |
Value
A list containing the processed data and metadata:
-
data: A list of data frames, one for each level ofsplit_by. If nosplit_byis provided, the name will be"...". Each data frame is in the long format. -
values_by: The name of the column containing the values to be plotted. -
rows_by: The name of the column containing the row information. -
rows_split_by: The name of the column containing the row split information. -
columns_by: The name of the column containing the column information. -
columns_split_by: The name of the column containing the column split information. -
pie_group_by: The name of the column containing the pie group information.
process_keep_na_empty Process keep_na and keep_empty to data
Description
process_keep_na_empty Process keep_na and keep_empty to data
Usage
process_keep_na_empty(data, keep_na = NULL, keep_empty = NULL, col = NULL)
Arguments
data |
data frame |
keep_na |
List of keep_na |
keep_empty |
List of keep_empty |
Value
processed data frame
Process data for LinkedHeatmap
Description
Process data for LinkedHeatmap
Usage
process_linkedheatmap_data(
data,
split_by,
split_by_sep,
rows_split_by,
rows_split_by_sep,
rows_split_name,
left_values_by,
left_name,
left_rows_by,
left_rows_by_sep,
left_rows_name,
left_rows_orderby,
left_columns_orderby,
left_columns_by,
left_columns_by_sep,
left_columns_name,
left_columns_split_by,
left_columns_split_by_sep,
left_columns_split_name,
left_pie_group_by,
left_pie_group_by_sep,
left_pie_name,
left_rows_data,
left_columns_data,
right_values_by,
right_name,
right_rows_by,
right_rows_by_sep,
right_rows_name,
right_rows_orderby,
right_columns_orderby,
right_columns_by,
right_columns_by_sep,
right_columns_name,
right_columns_split_by,
right_columns_split_by_sep,
right_columns_split_name,
right_pie_group_by,
right_pie_group_by_sep,
right_pie_name,
right_rows_data,
right_columns_data,
keep_na,
keep_empty
)
Process theme to allow 'ggplot2::theme_minimal' to work
Description
Process theme to allow 'ggplot2::theme_minimal' to work
Usage
process_theme(theme)
Arguments
theme |
The theme to process |
Value
The processed theme
Convert RGBA to RGB
Description
Convert RGBA to RGB
Usage
rgba_to_rgb(RGBA, BackGround = c(1, 1, 1))
Show the color palettes
Description
This function displays color palettes using ggplot2.
Usage
show_palettes(
palettes = NULL,
type = c("discrete", "continuous"),
index = NULL,
palette_names = NULL,
return_names = TRUE,
return_palettes = FALSE
)
Arguments
palettes |
A list of color palettes. If |
type |
A character vector specifying the type of palettes to include. Default is "discrete". |
index |
A numeric vector specifying the indices of the palettes to include. Default is |
palette_names |
A character vector specifying the names of the SCP palettes to include. Default is |
return_names |
A logical value indicating whether to return the names of the selected palettes. Default is |
return_palettes |
A logical value indicating whether to return the colors of selected palettes. Default is |
Value
A list of palette names or a list of palettes.
See Also
Examples
show_palettes(palettes = list(c("red", "blue", "green"), c("yellow", "purple", "orange")))
all_palettes <- show_palettes(return_palettes = TRUE)
names(all_palettes)
all_palettes[["simspec"]]
show_palettes(index = 1:10)
show_palettes(type = "discrete", index = 1:10)
show_palettes(type = "continuous", index = 1:10)
show_palettes(
palette_names = c("Paired", "nejm", "simspec", "Spectral", "jet"),
return_palettes = TRUE
)
Blank theme
Description
This function creates a theme with all elements blank except for axis lines and labels. It can optionally add coordinate axes in the plot.
Usage
theme_blank(
add_coord = TRUE,
xlen_npc = 0.15,
ylen_npc = 0.15,
xlab = "",
ylab = "",
lab_size = 12,
...
)
Arguments
add_coord |
Whether to add coordinate arrows. Default is |
xlen_npc |
The length of the x-axis arrow in "npc". |
ylen_npc |
The length of the y-axis arrow in "npc". |
xlab |
x-axis label. |
ylab |
y-axis label. |
lab_size |
Label size. |
... |
Arguments passed to the |
Value
A ggplot2 theme.
Examples
library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) +
geom_point()
p + theme_blank()
p + theme_blank(xlab = "x-axis", ylab = "y-axis", lab_size = 16)
Box theme
Description
This function creates a theme with all elements blank except for axis lines like a box around the plot.
Usage
theme_box(
xlen_npc = 0.15,
ylen_npc = 0.15,
xlab = "",
ylab = "",
lab_size = 12,
...
)
Arguments
xlen_npc |
The length of the x-axis arrow in "npc". |
ylen_npc |
The length of the y-axis arrow in "npc". |
xlab |
x-axis label. |
ylab |
y-axis label. |
lab_size |
Label size. |
... |
Arguments passed to the |
Value
A ggplot2 theme.
Examples
library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) +
geom_point()
p + theme_box()
A ggplot2 theme and palettes for plotthis
Borrowed from the theme_this function in the SCP pipeline
Description
A ggplot2 theme and palettes for plotthis
Borrowed from the theme_this function in the SCP pipeline
Usage
theme_this(aspect.ratio = NULL, base_size = NULL, font_family = NULL, ...)
Arguments
aspect.ratio |
The aspect ratio of the plot |
base_size |
The base size of the text
If not specified, it will use the value from |
font_family |
The font family of the text
If not specified, it will use the value from |
... |
Other arguments for |
Value
A ggplot2 theme
See Also
https://github.com/zhanghao-njmu/SCP
Validate common arguments
Description
Validate common arguments
Usage
validate_common_args(
seed,
facet_by = NULL,
plot_type = NULL,
split_by = NULL,
split_by_sep = "_",
group_by = NULL,
group_by_sep = "_",
facet_scales = "fixed",
facet_nrow = NULL,
facet_ncol = NULL,
facet_byrow = TRUE,
theme = "theme_this",
theme_args = list(),
palette = NULL,
palcolor = NULL,
expand = NULL,
keep_na = FALSE,
keep_empty = FALSE,
alpha = 1,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
combine = TRUE,
nrow = NULL,
ncol = NULL,
byrow = TRUE,
...
)
Arguments
seed |
The random seed to use. Default is 8525. |
facet_by |
A character string specifying the column name of the data frame to facet the plot.
Otherwise, the data will be split by |
split_by |
The column(s) to split data by and plot separately. |
split_by_sep |
The separator for multiple split_by columns. See |
group_by |
Columns to group the data for plotting
For those plotting functions that do not support multiple groups,
They will be concatenated into one column, using |
group_by_sep |
The separator for multiple group_by columns. See |
facet_scales |
Whether to scale the axes of facets. Default is "fixed"
Other options are "free", "free_x", "free_y". See |
facet_nrow |
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used. |
facet_ncol |
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used. |
facet_byrow |
A logical value indicating whether to fill the plots by row. Default is TRUE. |
theme |
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this". |
theme_args |
A list of arguments to pass to the theme function. |
palette |
A character string specifying the palette to use.
A named list or vector can be used to specify the palettes for different |
palcolor |
A character string specifying the color to use in the palette.
A named list can be used to specify the colors for different |
expand |
The values to expand the x and y axes. It is like CSS padding. When a single value is provided, it is used for both axes on both sides. When two values are provided, the first value is used for the top/bottom side and the second value is used for the left/right side. When three values are provided, the first value is used for the top side, the second value is used for the left/right side, and the third value is used for the bottom side. When four values are provided, the values are used for the top, right, bottom, and left sides, respectively. You can also use a named vector to specify the values for each side. When the axis is discrete, the values will be applied as 'add' to the 'expansion' function. When the axis is continuous, the values will be applied as 'mult' to the 'expansion' function. See also https://ggplot2.tidyverse.org/reference/expansion.html |
keep_na |
A logical value or a character to replace the NA values in the data.
It can also take a named list to specify different behavior for different columns.
If TRUE or NA, NA values will be replaced with NA.
If FALSE, NA values will be removed from the data before plotting.
If a character string is provided, NA values will be replaced with the provided string.
If a named vector/list is provided, the names should be the column names to apply the behavior to,
and the values should be one of TRUE, FALSE, or a character string.
Without a named vector/list, the behavior applies to categorical/character columns used on the plot,
for example, the |
keep_empty |
One of FALSE, TRUE and "level". It can also take a named list to specify
different behavior for different columns. Without a named list, the behavior applies to the
categorical/character columns used on the plot, for example, the
|
alpha |
A numeric value specifying the transparency of the plot. |
x_text_angle |
A numeric value specifying the angle of the x-axis text. |
aspect.ratio |
A numeric value specifying the aspect ratio of the plot. |
legend.position |
A character string specifying the position of the legend.
if |
legend.direction |
A character string specifying the direction of the legend. |
title |
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic. |
subtitle |
A character string specifying the subtitle of the plot. |
xlab |
A character string specifying the x-axis label. |
ylab |
A character string specifying the y-axis label. |
combine |
Whether to combine the plots into one when facet is FALSE. Default is TRUE. |
nrow |
A numeric value specifying the number of rows in the facet. |
ncol |
A numeric value specifying the number of columns in the facet. |
byrow |
A logical value indicating whether to fill the plots by row. |
... |
Additional arguments. |
Excluded words in keyword enrichment analysis and extraction
Description
The variable "words_excluded" represents the words that are excluded during keyword enrichment analysis or keyword extraction process. These mainly include words that are excessively redundant or of little value.
Examples
## Not run:
if (interactive()) {
words_excluded <- c(
"the", "is", "and", "or", "a", "in", "on", "under", "between", "of", "through",
"via", "along", "that", "for", "with", "within", "without", "cell", "cellular",
"dna", "rna", "protein", "peptide", "amino", "acid", "development", "involved",
"organization", "system", "regulation", "regulated", "positive", "negative",
"response", "process", "processing", "small", "large", "change", "disease"
)
}
## End(Not run)