| Title: | Utility Functions for Plotting |
|---|---|
| Description: | Provides utility functions for plotting. Includes functions for color manipulation, plot customization, panel size control, data optimization for plots, and layout adjustments. |
| Authors: | Meng Xu [aut, cre] (ORCID: <https://orcid.org/0000-0002-8300-1054>), Haoliang Zhu [aut] (ORCID: <https://orcid.org/0009-0004-9766-5179>) |
| Maintainer: | Meng Xu <[email protected]> |
| License: | MIT+ file LICENSE |
| Version: | 0.4.6 |
| Built: | 2026-10-13 12:17:10 UTC |
| Source: | https://github.com/mengxu98/thisplot |
Provides utility functions for data visualization and plotting in R. Includes functions for color manipulation, plot customization, panel size control, data optimization for plots, and layout adjustments. Designed to enhance workflows with ggplot2, patchwork, and ComplexHeatmap.
Meng Xu (Maintainer), [email protected]
https://mengxu98.github.io/thisplot/
Useful links:
Add a grob to a gtable at a specified position (top, bottom, left, or right).
add_grob( gtable, grob, position = c("top", "bottom", "left", "right", "none"), space = NULL, clip = "on" )add_grob( gtable, grob, position = c("top", "bottom", "left", "right", "none"), space = NULL, clip = "on" )
gtable |
A gtable object. |
grob |
A grob or gtable object to add. |
position |
The position to add the grob.
One of |
space |
The space to allocate for the grob.
If |
clip |
The clipping mode.
Default is |
A gtable object with the grob added.
Convert a color with specified alpha level
adjcolors(colors, alpha)adjcolors(colors, alpha)
colors |
Color vectors. |
alpha |
Alpha level in |
A character vector of hexadecimal color codes with the specified alpha level.
colors <- c("red", "blue", "green") adjcolors(colors, 0.5) ggplot2::alpha(colors, 0.5) show_palettes( list( "raw" = colors, "adjcolors" = adjcolors(colors, 0.5), "ggplot2::alpha" = ggplot2::alpha(colors, 0.5) ) )colors <- c("red", "blue", "green") adjcolors(colors, 0.5) ggplot2::alpha(colors, 0.5) show_palettes( list( "raw" = colors, "adjcolors" = adjcolors(colors, 0.5), "ggplot2::alpha" = ggplot2::alpha(colors, 0.5) ) )
Adjust the layout of a graph to prevent node overlaps by considering node widths and heights.
adjustlayout(graph, layout, width, height = 2, scale = 100, iter = 100)adjustlayout(graph, layout, width, height = 2, scale = 100, iter = 100)
graph |
An igraph graph object. |
layout |
A matrix with two columns representing the initial layout coordinates. |
width |
A numeric vector of node widths. |
height |
The height constraint for nodes.
Default is |
scale |
The scaling factor for the layout.
Default is |
iter |
The number of iterations for the adjustment algorithm.
Default is |
A matrix with adjusted layout coordinates.
Annotate plot quadrants with percentages
annotate_quadrants( plot, x, y, cutoffs, line_color = "grey30", line_type = "solid", line_width = 0.5, label_size = 3, group = NULL )annotate_quadrants( plot, x, y, cutoffs, line_color = "grey30", line_type = "solid", line_width = 0.5, label_size = 3, group = NULL )
plot |
A 'ggplot' object. |
x |
Name of the x variable in 'plot$data'. |
y |
Name of the y variable in 'plot$data'. |
cutoffs |
Cut points for x and y axes. Can be a numeric vector of length 1 or 2, or a list with the x and y cut points. |
line_color |
Quadrant line color. |
line_type |
Quadrant line type. |
line_width |
Quadrant line width. |
label_size |
Label size. |
group |
Optional grouping column used to compute percentages within each group. |
A 'ggplot' object.
df <- data.frame( x = c(0.1, 0.2, 0.8, 0.9), y = c(0.1, 0.8, 0.2, 0.9) ) p <- ggplot2::ggplot(df, ggplot2::aes(x = x, y = y)) + ggplot2::geom_point() p annotate_quadrants(p, x = "x", y = "y", cutoffs = 0.5)df <- data.frame( x = c(0.1, 0.2, 0.8, 0.9), y = c(0.1, 0.8, 0.2, 0.9) ) p <- ggplot2::ggplot(df, ggplot2::aes(x = x, y = y)) + ggplot2::geom_point() p annotate_quadrants(p, x = "x", y = "y", cutoffs = 0.5)
Build block fill panel function
annotation_block_fill_graphics( levels, palette = NULL, palcolor = NULL, fill_values = NULL, border = TRUE, border_color = "black", border_size = 1 )annotation_block_fill_graphics( levels, palette = NULL, palcolor = NULL, fill_values = NULL, border = TRUE, border_color = "black", border_size = 1 )
levels |
Character/factor levels used as keys for fill mapping. |
palette |
Palette name. All available palette names can be queried with show_palettes. |
palcolor |
Custom colors used to create a color palette. |
fill_values |
Optional named fill vector. Names should match |
border |
Whether to draw block border. |
border_color |
Border color when |
border_size |
Border line width when |
A function with signature (index, levels) suitable for panel_fun in ComplexHeatmap::anno_block.
Build block panel function
annotation_block_graphics( subplot, name, border = TRUE, border_color = "black", border_size = 1 )annotation_block_graphics( subplot, name, border = TRUE, border_color = "black", border_size = 1 )
subplot |
A single drawable subplot object. |
name |
A name assigned to the generated grob. |
border |
Whether to draw a rectangle border around the block. |
border_color |
Border color when |
border_size |
Border line width when |
A function with signature (index, levels) suitable for panel_fun in ComplexHeatmap::anno_block.
Build graphics callback list for anno_customize
annotation_graphics(subplots, prefix)annotation_graphics(subplots, prefix)
subplots |
A named list of subplot objects. |
prefix |
Prefix used to generate stable grob names. |
A named list of callback functions accepted by ComplexHeatmap::anno_customize.
Convert various plot objects (gList, patchwork, ggplot) to a grob object.
as_grob(plot, ...)as_grob(plot, ...)
plot |
A plot object (gList, patchwork, or ggplot). |
... |
Additional arguments passed to other functions. |
A grob object.
Convert various plot objects (gtable, grob, patchwork, ggplot) to a gtable object.
as_gtable(plot, ...)as_gtable(plot, ...)
plot |
A plot object (gtable, grob, patchwork, or ggplot). |
... |
Additional arguments passed to other functions. |
A gtable object.
Blend two colors with alpha channels using one of several blending modes: blend, average, screen, or multiply.
Blend2Color(C1, C2, mode = "blend")Blend2Color(C1, C2, mode = "blend")
C1 |
A list containing the first color RGB values and alpha channel. |
C2 |
A list containing the second color RGB values and alpha channel. |
mode |
The blending mode to use.
One of |
A list containing the blended RGB values and alpha channel.
Blends a list of colors using the specified blend mode
blendcolors(colors, mode = c("blend", "average", "screen", "multiply"))blendcolors(colors, mode = c("blend", "average", "screen", "multiply"))
colors |
Color vectors. |
mode |
Blend mode.
One of |
A character vector of hexadecimal color codes representing the blended color.
blend <- c( "red", "green", blendcolors(c("red", "green"), mode = "blend" ) ) average <- c( "red", "green", blendcolors(c("red", "green"), mode = "average" ) ) screen <- c( "red", "green", blendcolors(c("red", "green"), mode = "screen" ) ) multiply <- c( "red", "green", blendcolors(c("red", "green"), mode = "multiply" ) ) show_palettes( list( "blend" = blend, "average" = average, "screen" = screen, "multiply" = multiply ) )blend <- c( "red", "green", blendcolors(c("red", "green"), mode = "blend" ) ) average <- c( "red", "green", blendcolors(c("red", "green"), mode = "average" ) ) screen <- c( "red", "green", blendcolors(c("red", "green"), mode = "screen" ) ) multiply <- c( "red", "green", blendcolors(c("red", "green"), mode = "multiply" ) ) show_palettes( list( "blend" = blend, "average" = average, "screen" = screen, "multiply" = multiply ) )
Blend multiple colors with alpha channels into a single color using a specified blending mode.
BlendRGBList(Clist, mode = "blend", RGB_BackGround = c(1, 1, 1))BlendRGBList(Clist, mode = "blend", RGB_BackGround = c(1, 1, 1))
Clist |
A list of colors, where each color is a list containing RGB values and alpha channel. |
mode |
The blending mode to use.
One of |
RGB_BackGround |
The background RGB color to composite with.
Default is |
A numeric vector of RGB values.
Build HeatmapAnnotation with safe parameter merge
build_heatmap_annotation( annotations, which, show_annotation_name = TRUE, annotation_name_side = NULL, border = NULL, params = NULL )build_heatmap_annotation( annotations, which, show_annotation_name = TRUE, annotation_name_side = NULL, border = NULL, params = NULL )
annotations |
Named list of annotation components (for example, |
which |
Annotation direction ( |
show_annotation_name |
Whether to show annotation names. |
annotation_name_side |
Side for annotation names. |
border |
Whether to draw a rectangle border around the block. |
params |
Additional user parameters; duplicated keys are ignored if already set explicitly. |
A ComplexHeatmap::HeatmapAnnotation object.
Build a gtable from a patchwork object by arranging multiple plots according to the layout specification.
build_patchwork( x, guides = "auto", table_rows = 18, table_cols = 15, panel_row = 10, panel_col = 8 )build_patchwork( x, guides = "auto", table_rows = 18, table_cols = 15, panel_row = 10, panel_col = 8 )
x |
A patchwork object. |
guides |
How to handle guides.
Default is |
table_rows |
The number of rows in the table grid.
Default is |
table_cols |
The number of columns in the table grid.
Default is |
panel_row |
The row index for panels.
Default is |
panel_col |
The column index for panels.
Default is |
A gtable object.
A dataset containing optimized traditional Chinese colors. These colors are extracted from those books:
Chinese Traditional Colors - Color Aesthetics in the Forbidden City (ISBN: 9787521716054)
Chinese Beautiful Colors - The Most Chinese Culture Vol.3 (ISBN: 9781672897198)
Chinese Colors (ISBN: 9787558016479)
Chinese Journal of Chromatography (ISSN 1000-8713)
Chinese Color Atlas
Thanks to the author of the blog for providing the data.
data(chinese_colors) color_sets <- attr(chinese_colors, "color_sets") show_palettes( list( color_sets$Chinese, color_sets$ChineseSet8, color_sets$ChineseSet16, color_sets$ChineseSet32 ) ) # Use ChineseColors class cc <- ChineseColors() cc$visual_colors( loc_range = c(1, 180), num_per_row = 30, title = "Chinese Traditional Colors", name_type = "chinese" )data(chinese_colors) color_sets <- attr(chinese_colors, "color_sets") show_palettes( list( color_sets$Chinese, color_sets$ChineseSet8, color_sets$ChineseSet16, color_sets$ChineseSet32 ) ) # Use ChineseColors class cc <- ChineseColors() cc$visual_colors( loc_range = c(1, 180), num_per_row = 30, title = "Chinese Traditional Colors", name_type = "chinese" )
A color system based on Chinese traditional colors with 1058 colors.
ChineseColors()ChineseColors()
A ChineseColors object.
Detailed information can be found in print.ChineseColors().
chinese_colors for the dataset of Chinese traditional colors. get_chinese_palettes for getting Chinese color palettes. visual_colors for visualizing any color vector. get_colors for searching colors in dataset and palettes.
cc <- ChineseColors() cc # Get a color by pinyin get_colors("pinlan") # By number get_colors(44) # By hex code get_colors("#2B73AF") # Multiple colors get_colors("pinlan", "piao") get_colors(91:100) # Chinese names cc$visual_colors( loc_range = c(1, 180), num_per_row = 30, title = "Chinese Traditional Colors", name_type = "chinese" ) # pinyin as names cc$visual_colors( loc_range = c(1, 120), title = "Chinese Traditional Colors", name_type = "pinyin" ) # rgb as names cc$visual_colors( loc_range = c(1, 120), title = "Colors with RGB values", name_type = "rgb" ) # hex as names cc$visual_colors( loc_range = c(1, 120), title = "Colors with hex codes", name_type = "hex" )cc <- ChineseColors() cc # Get a color by pinyin get_colors("pinlan") # By number get_colors(44) # By hex code get_colors("#2B73AF") # Multiple colors get_colors("pinlan", "piao") get_colors(91:100) # Chinese names cc$visual_colors( loc_range = c(1, 180), num_per_row = 30, title = "Chinese Traditional Colors", name_type = "chinese" ) # pinyin as names cc$visual_colors( loc_range = c(1, 120), title = "Chinese Traditional Colors", name_type = "pinyin" ) # rgb as names cc$visual_colors( loc_range = c(1, 120), title = "Colors with RGB values", name_type = "rgb" ) # hex as names cc$visual_colors( loc_range = c(1, 120), title = "Colors with hex codes", name_type = "hex" )
Clip values to a symmetric range
clip_symmetric_range(data, value_col = "avg_log2FC")clip_symmetric_range(data, value_col = "avg_log2FC")
data |
A data frame. |
value_col |
Name of the numeric column to clip. |
A list containing the clipped data frame and clipping limits.
df <- data.frame(avg_log2FC = c(-10, -2, 0, 2, 10)) clip_symmetric_range(df)df <- data.frame(avg_log2FC = c(-10, -2, 0, 2, 10)) clip_symmetric_range(df)
Cluster within group
cluster_within_group2(mat, factor)cluster_within_group2(mat, factor)
mat |
A matrix of data |
factor |
A factor |
A dendrogram with ordered leaves
Convert color names to hexadecimal RGB color codes.
col2hex(cname)col2hex(cname)
cname |
A character vector of color names. |
A character vector of hexadecimal color codes.
Compute velocity on grid
compute_velocity_on_grid( x_emb, v_emb, density = 1, smooth = 0.5, n_neighbors = ceiling(n_obs/50), min_mass = 1, scale = 1, adjust_for_stream = FALSE, cutoff_perc = 5 )compute_velocity_on_grid( x_emb, v_emb, density = 1, smooth = 0.5, n_neighbors = ceiling(n_obs/50), min_mass = 1, scale = 1, adjust_for_stream = FALSE, cutoff_perc = 5 )
x_emb |
A matrix of dimension n_obs x n_dim specifying the embedding coordinates of the cells. |
v_emb |
A matrix of dimension n_obs x n_dim specifying the velocity vectors of the cells. |
density |
A numeric value specifying the density of the grid points along each dimension.
Default is |
smooth |
A numeric value specifying the smoothing factor for the velocity vectors.
Default is |
n_neighbors |
A numeric value specifying the number of nearest neighbors for each grid point.
Default is |
min_mass |
A numeric value specifying the minimum mass required for a grid point to be considered.
Default is |
scale |
A numeric value specifying the scaling factor for the velocity vectors.
Default is |
adjust_for_stream |
Whether to adjust the velocity vectors for streamlines.
Default is |
cutoff_perc |
A numeric value specifying the percentile cutoff for removing low-density grid points.
Default is |
A list with two components:
x_grid, the grid coordinates, and v_grid, the smoothed velocity vectors on the grid.
https://github.com/theislab/scvelo/blob/master/scvelo/plotting/velocity_embedding_grid.py
x_emb <- matrix( c( 0, 0, 1, 0, 0, 1, 1, 1 ), ncol = 2, byrow = TRUE ) v_emb <- matrix( c( 1, 0, 1, 0, 0, 1, 0, 1 ), ncol = 2, byrow = TRUE ) velocity_grid <- compute_velocity_on_grid( x_emb = x_emb, v_emb = v_emb, density = 0.1, n_neighbors = 2, adjust_for_stream = TRUE ) names(velocity_grid) dim(velocity_grid$x_grid) dim(velocity_grid$v_grid) head(velocity_grid$x_grid) head(velocity_grid$v_grid) grid_df <- expand.grid( x = velocity_grid$x_grid[1, ], y = velocity_grid$x_grid[2, ] ) plot_df <- data.frame( x = grid_df$x, y = grid_df$y, xend = grid_df$x + c(velocity_grid$v_grid[1, , ]) * 0.2, yend = grid_df$y + c(velocity_grid$v_grid[2, , ]) * 0.2 ) ggplot2::ggplot(plot_df) + ggplot2::geom_segment( ggplot2::aes(x = x, y = y, xend = xend, yend = yend), arrow = grid::arrow(length = grid::unit(0.12, "inches")), na.rm = TRUE ) + ggplot2::coord_equal()x_emb <- matrix( c( 0, 0, 1, 0, 0, 1, 1, 1 ), ncol = 2, byrow = TRUE ) v_emb <- matrix( c( 1, 0, 1, 0, 0, 1, 0, 1 ), ncol = 2, byrow = TRUE ) velocity_grid <- compute_velocity_on_grid( x_emb = x_emb, v_emb = v_emb, density = 0.1, n_neighbors = 2, adjust_for_stream = TRUE ) names(velocity_grid) dim(velocity_grid$x_grid) dim(velocity_grid$v_grid) head(velocity_grid$x_grid) head(velocity_grid$v_grid) grid_df <- expand.grid( x = velocity_grid$x_grid[1, ], y = velocity_grid$x_grid[2, ] ) plot_df <- data.frame( x = grid_df$x, y = grid_df$y, xend = grid_df$x + c(velocity_grid$v_grid[1, , ]) * 0.2, yend = grid_df$y + c(velocity_grid$v_grid[2, , ]) * 0.2 ) ggplot2::ggplot(plot_df) + ggplot2::geom_segment( ggplot2::aes(x = x, y = y, xend = xend, yend = yend), arrow = grid::arrow(length = grid::unit(0.12, "inches")), na.rm = TRUE ) + ggplot2::coord_equal()
Visualize observations on precomputed two-dimensional coordinates.
DimDataPlot( data, x, y, group.by = NULL, split.by = NULL, shape.by = NULL, show_na = FALSE, palette = "Chinese", palcolor = NULL, NA_color = "grey80", pt.size = 2, pt.alpha = 1, shape.values = NULL, add_mark = FALSE, mark_type = c("hull", "ellipse", "rect", "circle"), mark_expand = grid::unit(3, "mm"), mark_alpha = 0.1, mark_linetype = 1, label = FALSE, label.size = 4, label.fg = "black", label.bg = "white", label.bg.r = 0.1, label_repel = FALSE, label_repulsion = 20, label_point_size = 1, label_point_color = "black", label_segment_color = "black", add_origin = FALSE, origin.color = "grey30", origin.linetype = "dashed", origin.linewidth = 0.4, aspect.ratio = 1, title = NULL, subtitle = NULL, xlab = NULL, ylab = NULL, legend.position = "right", legend.direction = "vertical", legend.title = NULL, theme_use = "theme_this", theme_args = list(), seed = 11 )DimDataPlot( data, x, y, group.by = NULL, split.by = NULL, shape.by = NULL, show_na = FALSE, palette = "Chinese", palcolor = NULL, NA_color = "grey80", pt.size = 2, pt.alpha = 1, shape.values = NULL, add_mark = FALSE, mark_type = c("hull", "ellipse", "rect", "circle"), mark_expand = grid::unit(3, "mm"), mark_alpha = 0.1, mark_linetype = 1, label = FALSE, label.size = 4, label.fg = "black", label.bg = "white", label.bg.r = 0.1, label_repel = FALSE, label_repulsion = 20, label_point_size = 1, label_point_color = "black", label_segment_color = "black", add_origin = FALSE, origin.color = "grey30", origin.linetype = "dashed", origin.linewidth = 0.4, aspect.ratio = 1, title = NULL, subtitle = NULL, xlab = NULL, ylab = NULL, legend.position = "right", legend.direction = "vertical", legend.title = NULL, theme_use = "theme_this", theme_args = list(), seed = 11 )
data |
A data frame containing coordinates and optional grouping columns. |
x |
Name of the column used as the x-axis coordinate. |
y |
Name of the column used as the y-axis coordinate. |
group.by |
Name of the column used to color observations.
Default is |
split.by |
Name of the column used to split the plot into facets.
Default is |
shape.by |
Name of the column used to map point shapes.
Default is |
show_na |
Whether to keep missing values in |
palette |
Color palette name. Available palettes can be found in
show_palettes. Default is |
palcolor |
Custom colors used to create a color palette.
Default is |
NA_color |
Color used for missing values. |
pt.size |
Point size. |
pt.alpha |
Point transparency. |
shape.values |
Point shapes used when |
add_mark |
Whether to add marks around groups. Default is |
mark_type |
Type of mark to add around groups.
One of |
mark_expand |
Expansion of the mark around each group.
This is used for |
mark_alpha |
Transparency of the mark.
Default is |
mark_linetype |
Line type of the mark border.
Default is |
label |
Whether to label group centers. |
label.size |
Size of labels. |
label.fg |
Foreground color of labels. |
label.bg |
Background color of labels. |
label.bg.r |
Background ratio of labels. |
label_repel |
Whether labels repel from their group centers. |
label_repulsion |
Repulsion force for labels. |
label_point_size |
Size of center points for repelled labels. |
label_point_color |
Color of center points for repelled labels. |
label_segment_color |
Color of label segments. |
add_origin |
Whether to add dashed x = 0 and y = 0 reference lines. |
origin.color |
Color of origin reference lines. |
origin.linetype |
Line type of origin reference lines. |
origin.linewidth |
Line width of origin reference lines. |
aspect.ratio |
Aspect ratio passed to |
title |
Plot title. |
subtitle |
Plot subtitle. |
xlab |
Label for the x axis. |
ylab |
Label for the y axis. |
legend.position |
Position of the legend. |
legend.direction |
Direction of the legend. |
legend.title |
Title of the group legend. |
theme_use |
Theme function applied to the plot. |
theme_args |
A named list of arguments passed to |
seed |
Random seed. |
A ggplot object.
set.seed(1) plot_data <- data.frame( x = c(rnorm(40, -1), rnorm(40, 1)), y = c(rnorm(40, 0), rnorm(40, 1)), group = rep(c("A", "B"), each = 40) ) DimDataPlot( plot_data, x = "x", y = "y", group.by = "group" ) DimDataPlot( plot_data, x = "x", y = "y", group.by = "group", add_origin = TRUE, mark_type = "ellipse" ) DimDataPlot( plot_data, x = "x", y = "y", group.by = "group", mark_type = "circle", mark_alpha = 0.3, mark_expand = grid::unit(1, "mm"), mark_linetype = 2 )set.seed(1) plot_data <- data.frame( x = c(rnorm(40, -1), rnorm(40, 1)), y = c(rnorm(40, 0), rnorm(40, 1)), group = rep(c("A", "B"), each = 40) ) DimDataPlot( plot_data, x = "x", y = "y", group.by = "group" ) DimDataPlot( plot_data, x = "x", y = "y", group.by = "group", add_origin = TRUE, mark_type = "ellipse" ) DimDataPlot( plot_data, x = "x", y = "y", group.by = "group", mark_type = "circle", mark_alpha = 0.3, mark_expand = grid::unit(1, "mm"), mark_linetype = 2 )
Drop unused data points from a ggplot or patchwork object while preserving the plot structure. This function keeps only a single row of data for each unique combination of used variables, which can significantly reduce the object size when the original data contains many rows that are not displayed in the plot (e.g., due to scale limits or filtering).
drop_data(p) ## S3 method for class 'ggplot' drop_data(p) ## S3 method for class 'patchwork' drop_data(p) ## Default S3 method: drop_data(p)drop_data(p) ## S3 method for class 'ggplot' drop_data(p) ## S3 method for class 'patchwork' drop_data(p) ## Default S3 method: drop_data(p)
p |
A |
A ggplot or patchwork object with unused data points removed.
library(ggplot2) library(patchwork) p <- ggplot( data = mtcars, aes(x = mpg, y = wt, colour = cyl) ) + geom_point() + scale_x_continuous(limits = c(10, 30)) + scale_y_continuous(limits = c(1, 6)) object.size(p) p_drop <- drop_data(p) object.size(p_drop) p / p_droplibrary(ggplot2) library(patchwork) p <- ggplot( data = mtcars, aes(x = mpg, y = wt, colour = cyl) ) + geom_point() + scale_x_continuous(limits = c(10, 30)) + scale_y_continuous(limits = c(1, 6)) object.size(p) p_drop <- drop_data(p) object.size(p_drop) p / p_drop
Extract grobs from a named list of grobs based on the specified x and y indices.
extractgrobs(vlnplots, x_nm, y_nm, x, y)extractgrobs(vlnplots, x_nm, y_nm, x, y)
vlnplots |
A named list of grobs. |
x_nm |
A character vector of names for the x dimension. |
y_nm |
A character vector of names for the y dimension. |
x |
An integer index for the x dimension. |
y |
An integer index for the y dimension. |
The extracted grob(s).
Creates an alluvial plot which visualize flows between nodes. Each observation needs to have a 'x' aesthetic as well as a 'next_x' column which declares where that observation should flow. Also each observation should have a 'node' and a 'next_node' aesthetic which provide information about which group in the y-direction.
geom_alluvial( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = 0, width = 0.1, smooth = 8, inherit.aes = TRUE, ... )geom_alluvial( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = 0, width = 0.1, smooth = 8, inherit.aes = TRUE, ... )
mapping |
Provide you own mapping. Both x and y need to be numeric. |
data |
Provide you own data. |
position |
Change position. |
na.rm |
Remove missing values. |
show.legend |
Show legend in plot. |
space |
Space between nodes in the y-direction. |
width |
Width of nodes. |
smooth |
How much smooth should the curve have? More means steeper curve. |
inherit.aes |
Should the geom inherit aesthetics. |
... |
Other arguments to be passed to the geom. |
A ggplot layer.
Creates centered labels or text in nodes of your alluvial plot. Needs to have the exact same aesthetics as the call to 'geom_alluvial' to work.
geom_alluvial_text( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = 0, width = 0.1, inherit.aes = TRUE, ... ) geom_alluvial_label( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = 0, width = 0.1, inherit.aes = TRUE, ... )geom_alluvial_text( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = 0, width = 0.1, inherit.aes = TRUE, ... ) geom_alluvial_label( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = 0, width = 0.1, inherit.aes = TRUE, ... )
mapping |
Provide you own mapping. Both x and y need to be numeric. |
data |
Provide you own data. |
position |
Change position. |
na.rm |
Remove missing values. |
show.legend |
Show legend in plot. |
space |
Space between nodes in the y-direction. |
width |
Width of nodes. |
inherit.aes |
Should the geom inherit aesthetics. |
... |
Other arguments to be passed to the geom. |
Other important arguments are; 'space' which provides the space between nodes in the y-direction; 'shift' which shifts nodes in the y-direction.
A ggplot layer.
Creates a sankey plot which visualize flows between nodes. Each observation needs to have a 'x' aesthetic as well as a 'next_x' column which declares where that observation should flow. Also each observation should have a 'node' and a 'next_node' aesthetic which provide information about which group in the y-direction. By default each row of the data frame is counted to calculate the size of flows. A manual flow value can be added with the 'value' aesthetic.
geom_sankey( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = NULL, type = "sankey", width = 0.1, smooth = 8, inherit.aes = TRUE, ... )geom_sankey( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = NULL, type = "sankey", width = 0.1, smooth = 8, inherit.aes = TRUE, ... )
mapping |
Provide you own mapping. Both x and y need to be numeric. |
data |
Provide you own data. |
position |
Change position. |
na.rm |
Remove missing values. |
show.legend |
Show legend in plot. |
space |
Space between nodes in the y-direction. |
type |
Either 'sankey' or 'alluvial'. |
width |
Width of nodes. |
smooth |
How much smooth should the curve have? More means steeper curve. |
inherit.aes |
Should the geom inherit aesthetics. |
... |
Other arguments to be passed to the geom. |
A ggplot layer.
geom_sankey understand the following aesthetics (required aesthetics are in bold):
- **x0** - **y0** - **a** - **b** - **angle** - m1 - m2 - color - fill - size - linetype - alpha - lineend
dat <- data.frame( Group = c("A", "A", "B", "B", "C"), Type = c("X", "Y", "X", "Y", "X") ) long <- make_long(dat, Group, Type) ggplot2::ggplot( long, ggplot2::aes( x = x, next_x = next_x, node = node, next_node = next_node, fill = node ) ) + geom_sankey() + theme_sankey()dat <- data.frame( Group = c("A", "A", "B", "B", "C"), Type = c("X", "Y", "X", "Y", "X") ) long <- make_long(dat, Group, Type) ggplot2::ggplot( long, ggplot2::aes( x = x, next_x = next_x, node = node, next_node = next_node, fill = node ) ) + geom_sankey() + theme_sankey()
Creates a sankey bump plot which visualize flows between nodes. Each observation needs to have a 'x' aesthetic as well as a 'next_x' column which declares where that observation should flow. Also, each observation should have a 'node' and a 'next_node' aesthetic which provide information about which group in the y-direction.
geom_sankey_bump( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, smooth = 8, type = "sankey", inherit.aes = TRUE, ... )geom_sankey_bump( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, smooth = 8, type = "sankey", inherit.aes = TRUE, ... )
mapping |
Provide you own mapping. Both x and y need to be numeric. |
data |
Provide you own data. |
position |
Change position. |
na.rm |
Remove missing values. |
show.legend |
Show legend in plot. |
smooth |
How much smooth should the curve have? More means steeper curve. |
type |
Either 'sankey' or 'alluvial'. |
inherit.aes |
Should the geom inherit aesthetics. |
... |
Other arguments to be passed to the geom. |
Other important arguments are; 'space' which provides the space between nodes in the y-direction; 'shift' which shifts nodes in the y-direction.
A ggplot layer.
Creates centered labels or text in nodes of your sankey plot. Needs to have the exact same aesthetics as the call to 'geom_sankey' to work.
geom_sankey_label( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = NULL, type = "sankey", width = 0.1, inherit.aes = TRUE, ... ) geom_sankey_text( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = NULL, type = "sankey", width = 0.1, inherit.aes = TRUE, ... )geom_sankey_label( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = NULL, type = "sankey", width = 0.1, inherit.aes = TRUE, ... ) geom_sankey_text( mapping = NULL, data = NULL, position = "identity", na.rm = FALSE, show.legend = NA, space = NULL, type = "sankey", width = 0.1, inherit.aes = TRUE, ... )
mapping |
Provide you own mapping. Both x and y need to be numeric. |
data |
Provide you own data. |
position |
Change position. |
na.rm |
Remove missing values. |
show.legend |
Show legend in plot. |
space |
Space between nodes in the y-direction. |
type |
Either 'sankey' or 'alluvial'. |
width |
Width of nodes. |
inherit.aes |
Should the geom inherit aesthetics. |
... |
Other arguments to be passed to the geom. |
A ggplot layer.
Get Chinese color palettes
get_chinese_palettes(prefix = "Chinese")get_chinese_palettes(prefix = "Chinese")
prefix |
The prefix of the palette names. Default is '"Chinese_"'. |
A list of Chinese color palettes.
show_palettes(get_chinese_palettes())show_palettes(get_chinese_palettes())
Search for colors in the Chinese colors dataset and all available palettes. This function can search by palette names, color names (pinyin or Chinese), numbers, or hex codes. It automatically searches in all palettes and reports which palette(s) contain the found colors.
get_colors(..., palettes = NULL)get_colors(..., palettes = NULL)
... |
One or more search values.
Can be palette names, color names (pinyin or Chinese), numbers, or hex codes.
If NULL, using all Chinese colors.
Can also be |
palettes |
Optional. A named list of palettes to search in.
If |
A data frame with class colors containing matching color information.
The result is automatically printed using print.colors().
For ggplot or patchwork objects, returns a two-column colors data frame
with the factor levels (factor) and their mapped colors (color).
For other renderable plot objects, returns a two-column colors data frame
with the colors used in the plot (color) and their Chinese names (name).
chinese_colors for the dataset of Chinese traditional colors. get_chinese_palettes for getting Chinese color palettes. ChineseColors for the ChineseColors object.
get_colors("Paired") get_colors("#FF7F00") get_colors("pinlan") get_colors(44) get_colors("#2B73AF") get_colors("cyan", palettes = "ChineseSet64") # Get the factor-color mapping used in a ggplot object library(ggplot2) p <- ggplot(mtcars, aes(mpg, wt, color = factor(cyl))) + geom_point() + scale_color_manual(values = get_colors("Paired")$hex) get_colors(p)get_colors("Paired") get_colors("#FF7F00") get_colors("pinlan") get_colors(44) get_colors("#2B73AF") get_colors("cyan", palettes = "ChineseSet64") # Get the factor-color mapping used in a ggplot object library(ggplot2) p <- ggplot(mtcars, aes(mpg, wt, color = factor(cyl))) + geom_point() + scale_color_manual(values = get_colors("Paired")$hex) get_colors(p)
Extract the legend grob from a plot object. ggplot2 3.5+ places legends in
guide-box-left / right / top / bottom / inside slots; unused slots
are empty zeroGrobs. This helper returns the first non-empty legend, or
the legend at position when that argument is set.
get_legend(plot, position = NULL)get_legend(plot, position = NULL)
plot |
A plot object. |
position |
Optional legend position to extract. One of |
The legend grob, or NULL if the plot has no legend.
library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + geom_point() get_legend(p) get_legend(p + theme(legend.position = "bottom"), position = "bottom")library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + geom_point() get_legend(p) get_legend(p + theme(legend.position = "bottom"), position = "bottom")
Get used vars in a ggplot object
get_vars(p, reverse = FALSE, verbose = TRUE)get_vars(p, reverse = FALSE, verbose = TRUE)
p |
A |
reverse |
Whether to return unused vars.
Default is |
verbose |
Whether to print the message.
Default is |
A character vector of variable names.
If reverse is FALSE, returns used variables;
if TRUE, returns unused variables.
library(ggplot2) p <- ggplot( data = mtcars, aes(x = mpg, y = wt, colour = cyl) ) + geom_point() get_vars(p) get_vars(p, reverse = TRUE)library(ggplot2) p <- ggplot( data = mtcars, aes(x = mpg, y = wt, colour = cyl) ) + geom_point() get_vars(p) get_vars(p, reverse = TRUE)
A function to plot a graph with nodes and edges.
GraphPlot( node, edge, transition = NULL, node_coord = c("x", "y"), node_group = NULL, node_palette = "Chinese", node_palcolor = NULL, node_size = 4, node_alpha = 1, node_highlight = NULL, node_highlight_color = "red", label = FALSE, label.size = 3.5, label.fg = "white", label.bg = "black", label.bg.r = 0.1, label_insitu = FALSE, label_repel = FALSE, label_repulsion = 20, label_point_size = 1, label_point_color = "black", label_segment_color = "black", edge_threshold = 0.01, use_triangular = c("upper", "lower", "both"), edge_line = c("straight", "curved"), edge_line_curvature = 0.3, edge_line_angle = 90, edge_color = "grey30", edge_size = c(0.2, 1), edge_alpha = 0.5, edge_shorten = 0, edge_offset = 0, edge_highlight = NULL, edge_highlight_color = "red", transition_threshold = 0.01, transition_line = c("straight", "curved"), transition_line_curvature = 0.3, transition_line_angle = 90, transition_color = "black", transition_size = c(0.2, 1), transition_alpha = 1, transition_arrow_type = "closed", transition_arrow_angle = 20, transition_arrow_length = grid::unit(0.02, "npc"), transition_shorten = 0.05, transition_offset = 0, transition_highlight = NULL, transition_highlight_color = "red", aspect.ratio = 1, title = NULL, subtitle = NULL, xlab = NULL, ylab = NULL, legend.position = "right", legend.direction = "vertical", theme_use = "theme_this", theme_args = list(), return_layer = FALSE )GraphPlot( node, edge, transition = NULL, node_coord = c("x", "y"), node_group = NULL, node_palette = "Chinese", node_palcolor = NULL, node_size = 4, node_alpha = 1, node_highlight = NULL, node_highlight_color = "red", label = FALSE, label.size = 3.5, label.fg = "white", label.bg = "black", label.bg.r = 0.1, label_insitu = FALSE, label_repel = FALSE, label_repulsion = 20, label_point_size = 1, label_point_color = "black", label_segment_color = "black", edge_threshold = 0.01, use_triangular = c("upper", "lower", "both"), edge_line = c("straight", "curved"), edge_line_curvature = 0.3, edge_line_angle = 90, edge_color = "grey30", edge_size = c(0.2, 1), edge_alpha = 0.5, edge_shorten = 0, edge_offset = 0, edge_highlight = NULL, edge_highlight_color = "red", transition_threshold = 0.01, transition_line = c("straight", "curved"), transition_line_curvature = 0.3, transition_line_angle = 90, transition_color = "black", transition_size = c(0.2, 1), transition_alpha = 1, transition_arrow_type = "closed", transition_arrow_angle = 20, transition_arrow_length = grid::unit(0.02, "npc"), transition_shorten = 0.05, transition_offset = 0, transition_highlight = NULL, transition_highlight_color = "red", aspect.ratio = 1, title = NULL, subtitle = NULL, xlab = NULL, ylab = NULL, legend.position = "right", legend.direction = "vertical", theme_use = "theme_this", theme_args = list(), return_layer = FALSE )
node |
A data frame representing the nodes of the graph. |
edge |
A matrix representing the edges of the graph. |
transition |
A matrix representing the transitions between nodes. |
node_coord |
A character vector specifying the names of the columns in |
node_group |
A character vector specifying the name of the column in |
node_palette |
A character vector specifying the name of the color palette for node groups. |
node_palcolor |
A character vector specifying the names of the colors for each node group. |
node_size |
A numeric value or column name of |
node_alpha |
A numeric value or column name of |
node_highlight |
A character vector specifying the names of nodes to highlight. |
node_highlight_color |
A character vector specifying the color for highlighting nodes. |
label |
Whether to show labels for the nodes. |
label.size |
The size of the labels. |
label.fg |
A character vector specifying the foreground color of the labels. |
label.bg |
A character vector specifying the background color of the labels. |
label.bg.r |
The background color transparency of the labels. |
label_insitu |
Whether to display the node group labels in situ or as numeric values. |
label_repel |
Whether to use force-directed label repulsion. |
label_repulsion |
The repulsion force for labels. |
label_point_size |
The size of the label points. |
label_point_color |
A character vector specifying the color of the label points. |
label_segment_color |
A character vector specifying the color for the label segments. |
edge_threshold |
The threshold for removing edges. |
use_triangular |
A character vector specifying which part of the edge matrix to use (upper, lower, both). |
edge_line |
A character vector specifying the type of line for edges (straight, curved). |
edge_line_curvature |
The curvature of curved edges. |
edge_line_angle |
The angle of curved edges. |
edge_color |
A character vector specifying the color of the edges. |
edge_size |
A numeric vector specifying the range of edge sizes. |
edge_alpha |
The transparency of the edges. |
edge_shorten |
The length of the edge shorten. |
edge_offset |
The length of the edge offset. |
edge_highlight |
A character vector specifying the names of edges to highlight. |
edge_highlight_color |
A character vector specifying the color for highlighting edges. |
transition_threshold |
The threshold for removing transitions. |
transition_line |
A character vector specifying the type of line for transitions (straight, curved). |
transition_line_curvature |
The curvature of curved transitions. |
transition_line_angle |
The angle of curved transitions. |
transition_color |
A character vector specifying the color of the transitions. |
transition_size |
A numeric vector specifying the range of transition sizes. |
transition_alpha |
The transparency of the transitions. |
transition_arrow_type |
A character vector specifying the type of arrow for transitions (closed, open). |
transition_arrow_angle |
The angle of the transition arrow. |
transition_arrow_length |
The length of the transition arrow. |
transition_shorten |
The length of the transition shorten. |
transition_offset |
The length of the transition offset. |
transition_highlight |
A character vector specifying the names of transitions to highlight. |
transition_highlight_color |
A character vector specifying the color for highlighting transitions. |
aspect.ratio |
Aspect ratio passed to |
title |
Plot title. |
subtitle |
Plot subtitle. |
xlab |
Label for the x axis. |
ylab |
Label for the y axis. |
legend.position |
Legend position passed to |
legend.direction |
Legend direction passed to |
theme_use |
Theme function applied to the plot. |
theme_args |
A named list of arguments passed to |
return_layer |
Whether to return the plot layers as a list.
Defaults is |
node <- data.frame( x = c(0.2, 0.3, 0.5, 0.3), y = c(0.2, 0, 0.6, 0.7), group = c("A", "B", "C", "B"), row.names = c("n1", "n2", "n3", "n4") ) edge <- matrix( c( 0, 0.4, 0.2, 0.1, 0.4, 0, 0.3, 0.2, 0.2, 0.3, 0, 0.5, 0.2, 0.2, 0.5, 0.3 ), nrow = 4, byrow = TRUE, dimnames = list(rownames(node), rownames(node)) ) GraphPlot( node = node, edge = edge ) GraphPlot( node = node, edge = edge, node_group = "group", node_highlight = "n1", label = TRUE, label_repel = TRUE )node <- data.frame( x = c(0.2, 0.3, 0.5, 0.3), y = c(0.2, 0, 0.6, 0.7), group = c("A", "B", "C", "B"), row.names = c("n1", "n2", "n3", "n4") ) edge <- matrix( c( 0, 0.4, 0.2, 0.1, 0.4, 0, 0.3, 0.2, 0.2, 0.3, 0, 0.5, 0.2, 0.2, 0.5, 0.3 ), nrow = 4, byrow = TRUE, dimnames = list(rownames(node), rownames(node)) ) GraphPlot( node = node, edge = edge ) GraphPlot( node = node, edge = edge, node_group = "group", node_highlight = "n1", label = TRUE, label_repel = TRUE )
Draw a list of grobs at specified positions with given widths and heights.
grid_draw(groblist, x, y, width, height)grid_draw(groblist, x, y, width, height)
groblist |
A grob or a list of grobs to draw. |
x |
A numeric vector of x positions for each grob. |
y |
A numeric vector of y positions for each grob. |
width |
A numeric vector of widths for each grob. |
height |
A numeric vector of heights for each grob. |
No return value, called for side effects (drawing grobs).
Returns the first part of a colors object, similar to head() for data frames.
## S3 method for class 'colors' head(x, n = 6L, ...)## S3 method for class 'colors' head(x, n = 6L, ...)
x |
A colors object (data frame with color information). |
n |
Number of rows to return. Default is |
... |
Additional arguments passed to |
A colors object with the first n rows.
head(get_colors()) head(get_colors(), n = 10)head(get_colors()) head(get_colors(), n = 10)
Normalize a heatmap border flag, optional colour override, and line width into values accepted by 'ComplexHeatmap::Heatmap' and 'ComplexHeatmap::Legend'.
heatmap_border_spec(border = NULL, palcolor = "black", size = 1) heatmap_border_enabled(border) heatmap_border_color(border, palcolor = "black") heatmap_border_size_value(size) heatmap_border_gp(border, color, size = 1) heatmap_legend_border(border, color)heatmap_border_spec(border = NULL, palcolor = "black", size = 1) heatmap_border_enabled(border) heatmap_border_color(border, palcolor = "black") heatmap_border_size_value(size) heatmap_border_gp(border, color, size = 1) heatmap_legend_border(border, color)
border |
'NULL', a logical border flag, or a non-empty colour string. |
palcolor |
Fallback border colour when 'border' is not a colour string. |
size |
Border line width. Invalid or negative values use '1'. |
color |
Fallback border colour used by the 'gp' and legend helpers. |
A list with 'enabled', 'color', 'size', 'gp', and 'legend_border'.
Compute fixed heatmap device size
heatmap_fixsize( width, width_sum, height, height_sum, units, ht_list, legend_list )heatmap_fixsize( width, width_sum, height, height_sum, units, ht_list, legend_list )
width |
Optional user-provided target width. If |
width_sum |
Numeric baseline width used when heatmap body size is in
|
height |
Optional user-provided target height. If |
height_sum |
Numeric baseline height used when heatmap body size is in
|
units |
Output unit string passed to grid conversion helpers, such as
|
ht_list |
A |
legend_list |
A list of |
A list with two converted units: ht_width and ht_height.
Estimate heatmap render size
heatmap_rendersize( width, height, units, ha_top_list, ha_left, ha_right, ht_list, legend_list, flip )heatmap_rendersize( width, height, units, ha_top_list, ha_left, ha_right, ht_list, legend_list, flip )
width |
Numeric vector of heatmap body widths.
Interpretation depends on |
height |
Numeric vector of heatmap body heights.
Interpretation depends on |
units |
Unit string for numeric-to-grid conversion (for example, |
ha_top_list |
A list of top annotations (typically |
ha_left |
Optional left annotation. |
ha_right |
Optional right annotation. |
ht_list |
A |
legend_list |
A list containing legend objects; |
flip |
Logical; when |
A list with numeric width_sum and height_sum in units.
Build dark-mode variants of several figures at once, dispatching on the file
extension: SVG files are inverted with invert_svg() and PNG files with
invert_png(). Every output is written next to its input, or into
output_dir, with a -dark suffix added to the name. Files that already
carry the suffix are skipped, so running the function twice does not
complement the dark variants again.
invert_figures( path, output_dir = NULL, suffix = "-dark", recursive = FALSE, quiet = FALSE )invert_figures( path, output_dir = NULL, suffix = "-dark", recursive = FALSE, quiet = FALSE )
path |
Path(s) to figure files, or to directories holding them. |
output_dir |
Directory the dark variants are written to. Default is next to each input file. |
suffix |
Suffix added to the file name of every dark variant. Default
is |
recursive |
Whether a directory is scanned recursively. Default is
|
quiet |
Whether to suppress the per-file messages. Default is |
Other formats are not supported: there is no way to rewrite the colours of a
PDF from R without rasterising it first. Re-render the figure as SVG or PNG
where possible, for instance with ggsave(), or rasterise the PDF before
inverting it. Unsupported files are only reported when they are passed as a
file; a directory is scanned for the supported extensions.
The paths of the written files, invisibly.
Build a dark-mode variant of a PNG image by replacing every colour channel with its RGB complement. The alpha channel is kept as it is, so a transparent background stays transparent.
invert_png(path, output = NULL, quiet = FALSE)invert_png(path, output = NULL, quiet = FALSE)
path |
Path to the input PNG file. |
output |
Path of the output PNG. Defaults to the input name with a
|
quiet |
Whether to suppress the message about the written file.
Default is |
The output path, invisibly.
Build a dark-mode variant of an SVG image by replacing every colour with its
RGB complement. Both the hexadecimal notation used by svglite and the
rgb() notation written by cairo-based devices such as grDevices::svg()
are understood. Elements that do not set their own fill would keep the SVG
default black, so default_fill is written on the root <svg> element,
where those elements inherit it.
invert_svg( path, output = NULL, default_fill = "#ffffff", invert_raster = TRUE, quiet = FALSE )invert_svg( path, output = NULL, default_fill = "#ffffff", invert_raster = TRUE, quiet = FALSE )
path |
Path to the input SVG file. |
output |
Path of the output SVG. Defaults to the input name with a
|
default_fill |
Fill written on the root |
invert_raster |
Whether to complement the colours of embedded raster
images as well. Default is |
quiet |
Whether to suppress the message about the written file.
Default is |
The output path, invisibly, or the modified SVG as a string when
output is NA.
Jitter highlighted points deterministically
jitter_highlighted_points( data, jitter_width = 0.2, jitter_height = 0.2, seed = 11 )jitter_highlighted_points( data, jitter_width = 0.2, jitter_height = 0.2, seed = 11 )
data |
A data frame containing 'x', 'y', and 'border' columns. |
jitter_width |
Width of the x jitter. |
jitter_height |
Height of the y jitter. |
seed |
Numeric value used to offset the deterministic sequence. |
A data frame with 'x_plot' and 'y_plot' columns.
df <- data.frame( x = c(0, 1), y = c(0, 1), border = c(FALSE, TRUE) ) jitter_highlighted_points(df, jitter_width = 0.2, jitter_height = 0.2)df <- data.frame( x = c(0, 1), y = c(0, 1), border = c(FALSE, TRUE) ) jitter_highlighted_points(df, jitter_width = 0.2, jitter_height = 0.2)
Add or remove major grid lines from a ggplot object.
major_grid( plot, grid_major = TRUE, grid_major_colour = "grey80", grid_major_linetype = 2, grid_major_linewidth = 0.3 )major_grid( plot, grid_major = TRUE, grid_major_colour = "grey80", grid_major_linetype = 2, grid_major_linewidth = 0.3 )
plot |
A ggplot object. |
grid_major |
Whether to show major grid lines. Default is |
grid_major_colour |
Grid line colour. Default is |
grid_major_linetype |
Grid line type. Default is |
grid_major_linewidth |
Grid line width. Default is |
A ggplot object with modified panel.grid.major theme element.
library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() major_grid(p, grid_major = TRUE)library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() major_grid(p, grid_major = TRUE)
Prepares a 'wide' data frame into a format that 'geom_sankey' or 'geom_alluvial' understands. Useful to show flows between dimensions in dataset.
make_long(.df, ..., value = NULL)make_long(.df, ..., value = NULL)
.df |
a data frame |
... |
unquoted columnnames of df that you want to include in the plot. |
value |
if each row have a weight this weight could be kept by providing column name of weight. |
a longer data frame
Estimate the fuzzifier parameter m for fuzzy clustering based on the data dimensions.
mestimate(data)mestimate(data)
data |
A matrix or data frame. |
The estimated fuzzifier parameter m.
Network Plot
NetworkPlot( edge, node = NULL, from = "from", to = "to", weight = "weight", node_name = NULL, edge_group = NULL, edge_palcolor = NULL, edge_palette = "Chinese", node_group = NULL, node_palcolor = NULL, node_palette = "Chinese", node_shape = NULL, node_shape_values = NULL, node_size = NULL, node_size_range = NULL, layout = c("fr", "kk", "circle", "none"), node_coord = c("x", "y"), edge_width = c(0.2, 1), edge_width_legend = FALSE, edge_alpha = 0.7, edge_curvature = 0, edge_arrow = FALSE, label = TRUE, label_nodes = NULL, label.size = 3.5, label_size = NULL, label_face = NULL, label.fg = "black", label.bg = "white", label.bg.r = 0.1, highlight = NULL, highlight.color = "red", highlight.size = 6, title = NULL, aspect.ratio = 1, legend.position = "right", theme_use = "theme_this", theme_args = list(), seed = 42 )NetworkPlot( edge, node = NULL, from = "from", to = "to", weight = "weight", node_name = NULL, edge_group = NULL, edge_palcolor = NULL, edge_palette = "Chinese", node_group = NULL, node_palcolor = NULL, node_palette = "Chinese", node_shape = NULL, node_shape_values = NULL, node_size = NULL, node_size_range = NULL, layout = c("fr", "kk", "circle", "none"), node_coord = c("x", "y"), edge_width = c(0.2, 1), edge_width_legend = FALSE, edge_alpha = 0.7, edge_curvature = 0, edge_arrow = FALSE, label = TRUE, label_nodes = NULL, label.size = 3.5, label_size = NULL, label_face = NULL, label.fg = "black", label.bg = "white", label.bg.r = 0.1, highlight = NULL, highlight.color = "red", highlight.size = 6, title = NULL, aspect.ratio = 1, legend.position = "right", theme_use = "theme_this", theme_args = list(), seed = 42 )
edge |
A data frame with one row per edge. |
node |
Optional data frame with one row per node. Node identifiers are
taken from |
from, to
|
Column names in |
weight |
Column name in |
node_name |
Column name in |
edge_group |
Optional column name in |
edge_palcolor, edge_palette
|
Custom colors or palette name for
|
node_group |
Optional column name in |
node_palcolor, node_palette
|
Custom colors or palette name for
|
node_shape |
Optional node shapes. Either a column name in |
node_shape_values |
Named vector mapping |
node_size |
Optional node sizes. Either a column name in |
node_size_range |
Optional size range used to rescale a numeric column
supplied to |
layout |
Layout used when |
node_coord |
Column names in |
edge_width |
Width range for the edges; |
edge_width_legend |
Whether to show the edge width legend. Default is
|
edge_alpha |
Edge alpha. |
edge_curvature |
Edge curvature passed to |
edge_arrow |
Whether to draw arrow heads on edges. |
label |
Whether to draw node labels. |
label_nodes |
Nodes to label. Default labels every node. |
label.size |
Label text size. |
label_size |
Optional per-node label sizes. Either a column name in
|
label_face |
Optional per-node label faces. Either a column name in
|
label.fg, label.bg, label.bg.r
|
Label foreground color, outline color and outline radius. |
highlight |
Optional node names drawn with an extra ring. |
highlight.color, highlight.size
|
Color and size of the highlight ring. |
title |
Optional plot title. |
aspect.ratio |
Aspect ratio passed to the theme. |
legend.position |
Legend position passed to the theme. |
theme_use |
Theme function name, one of |
theme_args |
A named list of arguments passed to |
seed |
Optional integer seed for the layout. |
A ggplot object.
edge <- data.frame( from = c("A", "A", "B", "C"), to = c("B", "C", "C", "D"), weight = c(1, -2, 3, 1) ) NetworkPlot(edge) node <- data.frame( name = c("A", "B", "C", "D"), group = c("g1", "g2", "g2", "g3"), shape = c("hub", "leaf", "leaf", "leaf") ) NetworkPlot( edge, node = node, node_group = "group", node_shape = "shape", node_shape_values = c("hub" = 23, "leaf" = 21), label_nodes = c("A", "B") )edge <- data.frame( from = c("A", "A", "B", "C"), to = c("B", "C", "C", "D"), weight = c(1, -2, 3, 1) ) NetworkPlot(edge) node <- data.frame( name = c("A", "B", "C", "D"), group = c("g1", "g2", "g2", "g3"), shape = c("hub", "leaf", "leaf", "leaf") ) NetworkPlot( edge, node = node, node_group = "group", node_shape = "shape", node_shape_values = c("hub" = 23, "leaf" = 21), label_nodes = c("A", "B") )
Remove the legend
no_legend()no_legend()
A ggplot2 theme object.
library(ggplot2) ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + geom_point() + no_legend()library(ggplot2) ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + geom_point() + no_legend()
Remove plot margins
no_margin()no_margin()
A ggplot2 theme object.
library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point() + no_margin()library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point() + no_margin()
Remove x-axis text and ticks
no_x_text()no_x_text()
A ggplot2 theme object.
library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point() + no_x_text()library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point() + no_x_text()
Remove y-axis text and ticks
no_y_text()no_y_text()
A ggplot2 theme object.
library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point() + no_y_text()library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point() + no_y_text()
Normalize drawable objects to grobs
normalize_drawable(obj)normalize_drawable(obj)
obj |
A drawable object, such as a ggplot, patchwork, or grid grob. |
A grid grob object. If the input is not drawable, returns a null grob.
library(ggplot2) p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() g <- normalize_drawable(p) p + glibrary(ggplot2) p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() g <- normalize_drawable(p) p + g
This function creates a color palette for a given vector of values.
palette_colors( x, n = 100, palette = "Chinese", palcolor = NULL, type = c("auto", "discrete", "continuous"), matched = FALSE, reverse = FALSE, NA_keep = FALSE, NA_color = "grey80" )palette_colors( x, n = 100, palette = "Chinese", palcolor = NULL, type = c("auto", "discrete", "continuous"), matched = FALSE, reverse = FALSE, NA_keep = FALSE, NA_color = "grey80" )
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 show_palettes. |
palcolor |
Custom colors used to create a color palette. |
type |
Type of |
matched |
Whether to return a color vector of the same length as |
reverse |
Whether to invert the colors.
Default is |
NA_keep |
Whether to keep the color assignment to NA in |
NA_color |
Color assigned to NA if |
A character vector of color codes (hexadecimal format) corresponding to the input values x. The length and structure depend on the matched parameter.
x <- c(1:3, NA, 3:5) (pal1 <- palette_colors( x, palette = "Spectral" )) (pal2 <- palette_colors( x, palcolor = c("red", "white", "blue") )) (pal3 <- palette_colors( x, palette = "Spectral", n = 10 )) (pal4 <- palette_colors( x, palette = "Spectral", n = 10, reverse = TRUE )) (pal5 <- palette_colors( x, palette = "Spectral", matched = TRUE )) (pal6 <- palette_colors( x, palette = "Spectral", matched = TRUE, NA_keep = TRUE )) show_palettes( list(pal1, pal2, pal3, pal4, pal5, pal6) ) # Use Chinese color palettes palette_colors( x = letters[1:5], palette = "ChineseRed", type = "discrete" ) palette_colors( x = letters[1:5], palette = "Chinese", type = "discrete" ) all_palettes <- show_palettes(return_palettes = TRUE) names(all_palettes)x <- c(1:3, NA, 3:5) (pal1 <- palette_colors( x, palette = "Spectral" )) (pal2 <- palette_colors( x, palcolor = c("red", "white", "blue") )) (pal3 <- palette_colors( x, palette = "Spectral", n = 10 )) (pal4 <- palette_colors( x, palette = "Spectral", n = 10, reverse = TRUE )) (pal5 <- palette_colors( x, palette = "Spectral", matched = TRUE )) (pal6 <- palette_colors( x, palette = "Spectral", matched = TRUE, NA_keep = TRUE )) show_palettes( list(pal1, pal2, pal3, pal4, pal5, pal6) ) # Use Chinese color palettes palette_colors( x = letters[1:5], palette = "ChineseRed", type = "discrete" ) palette_colors( x = letters[1:5], palette = "Chinese", type = "discrete" ) all_palettes <- show_palettes(return_palettes = TRUE) names(all_palettes)
A list of palettes for use in data visualization
The ggplot object, when stored, can only specify the height and width of the entire plot, not the panel. The latter is obviously more important to control the final result of a plot. This function can set the panel width/height of plot to a fixed value and rasterize it.
panel_fix( x = NULL, panel_index = NULL, respect = NULL, width = NULL, height = NULL, margin = 1, padding = 0, units = "in", raster = FALSE, dpi = 300, return_grob = FALSE, bg_color = "white", save = NULL, verbose = FALSE, ... ) panel_fix_overall( x, panel_index = NULL, respect = NULL, width = NULL, height = NULL, margin = 1, units = "in", raster = FALSE, dpi = 300, return_grob = FALSE, bg_color = "white", save = NULL, verbose = TRUE )panel_fix( x = NULL, panel_index = NULL, respect = NULL, width = NULL, height = NULL, margin = 1, padding = 0, units = "in", raster = FALSE, dpi = 300, return_grob = FALSE, bg_color = "white", save = NULL, verbose = FALSE, ... ) panel_fix_overall( x, panel_index = NULL, respect = NULL, width = NULL, height = NULL, margin = 1, units = "in", raster = FALSE, dpi = 300, return_grob = FALSE, bg_color = "white", save = NULL, verbose = TRUE )
x |
A ggplot object, a grob object, or a combined plot made by patchwork or cowplot package. |
panel_index |
Specify the panel to be fixed.
If |
respect |
Whether row heights and column widths should respect each other. |
width |
The desired width of the fixed panels. |
height |
The desired height of the fixed panels. |
margin |
The margin to add around each panel, in inches.
Default is |
padding |
The padding to add around each panel, in inches.
Default is |
units |
The units in which |
raster |
Whether to rasterize the panel. |
dpi |
Plot resolution. |
return_grob |
Whether to return a grob object instead of a wrapped |
bg_color |
The background color of the plot. |
save |
|
verbose |
Whether to print the message.
Default is |
... |
Additional arguments passed to other functions. |
If return_grob is TRUE, returns a gtable object.
Otherwise, returns a patchwork object with fixed panel sizes.
The returned object has a size attribute containing width, height, and units.
library(ggplot2) p <- ggplot( data = mtcars, aes(x = mpg, y = wt, colour = cyl) ) + geom_point() + facet_wrap(~gear, nrow = 2) # fix the size of panel panel_fix( p, width = 5, height = 3, units = "cm" ) # rasterize the panel panel_fix( p, width = 5, height = 3, units = "cm", raster = TRUE, dpi = 90 ) # `panel_fix` will build and render the plot when input a ggplot object. # so after `panel_fix`, the size of the object will be changed. object.size(p) object.size( panel_fix( p, width = 5, height = 3, units = "cm" ) )library(ggplot2) p <- ggplot( data = mtcars, aes(x = mpg, y = wt, colour = cyl) ) + geom_point() + facet_wrap(~gear, nrow = 2) # fix the size of panel panel_fix( p, width = 5, height = 3, units = "cm" ) # rasterize the panel panel_fix( p, width = 5, height = 3, units = "cm", raster = TRUE, dpi = 90 ) # `panel_fix` will build and render the plot when input a ggplot object. # so after `panel_fix`, the size of the object will be changed. object.size(p) object.size( panel_fix( p, width = 5, height = 3, units = "cm" ) )
Convert a patchwork object to a gtable grob by processing annotations and building the patchwork layout.
patchwork_grob(x, ...)patchwork_grob(x, ...)
x |
A patchwork object. |
... |
Additional arguments passed to other functions. |
A gtable object.
Calculate each plot's preferred physical size and keep every plot at that size. The default publication layout searches compact asymmetric placements with aligned edges, while the ordered layout packs shorter rows continuously and centers them. Apply plot-specific styling before composing.
plot_autocompose( plots, ncol = NULL, nrow = NULL, panel_width = 45, panel_height = 35, margin = 2, units = "mm", save = NULL, dpi = 300, base_size = "auto", label_autosize = TRUE, target_aspect = 1.6, target_width = NULL, layout = c("publication", "rows"), gutter = 4 )plot_autocompose( plots, ncol = NULL, nrow = NULL, panel_width = 45, panel_height = 35, margin = 2, units = "mm", save = NULL, dpi = 300, base_size = "auto", label_autosize = TRUE, target_aspect = 1.6, target_width = NULL, layout = c("publication", "rows"), gutter = 4 )
plots |
A plot or list of plots accepted by |
ncol, nrow
|
Number of columns and rows. Supplying either uses the ordered row layout. |
panel_width, panel_height
|
Base panel width and height. |
margin |
Outer margin. |
units |
Units for panel dimensions and margin. See |
save |
|
dpi |
Resolution used when saving raster output. |
base_size |
|
label_autosize |
Whether to enlarge constant |
target_aspect |
Preferred overall width-to-height ratio when |
target_width |
Optional publication target width in |
layout |
|
gutter |
Space between components in |
A wrapped plot with size and autosize attributes. Component sizes
are stored in attr(x, "autosize")$components.
p1 <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() p2 <- p1 + ggplot2::labs(title = "A wider plot title") plot_autocompose(list(p1, p2), ncol = 2)p1 <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() p2 <- p1 + ggplot2::labs(title = "A wider plot title") plot_autocompose(list(p1, p2), ncol = 2)
Build a compact plot by choosing a physical panel size and expanding it for
dense in-panel text or overflowing plot labels. A shared point-size baseline
harmonizes ggplot, patchwork, and recorded grid text such as wrapped
ComplexHeatmap output while preserving their relative hierarchy. Constant
data-label text is enlarged conservatively when space permits. The
calculation delegates final layout and saving to
panel_fix() while preserving label content, fixed aspect ratios, patchwork
layouts, and that function's behaviour.
plot_autosize( x, panel_width = 45, panel_height = 35, margin = 2, units = "mm", save = NULL, dpi = 300, base_size = "auto", label_autosize = TRUE, verbose = FALSE )plot_autosize( x, panel_width = 45, panel_height = 35, margin = 2, units = "mm", save = NULL, dpi = 300, base_size = "auto", label_autosize = TRUE, verbose = FALSE )
x |
A ggplot object, grob, or combined plot accepted by |
panel_width, panel_height
|
Base panel width and height. |
margin |
Outer margin. |
units |
Units for panel dimensions and margin. See |
save |
|
dpi |
Resolution used when saving raster output. |
base_size |
|
label_autosize |
Whether to enlarge constant |
verbose |
Whether to report messages from |
A plot with size and autosize attributes. Ordinary plots are
returned through panel_fix(); wrapped grid content is preserved directly.
library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + geom_point() p1 <- p + labs(title = "Fuel economy by vehicle weight") p1 p2 <- plot_autosize(p) p2 attr(p2, "size") plot_autosize(p1)library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + geom_point() p1 <- p + labs(title = "Fuel economy by vehicle weight") p1 p2 <- plot_autosize(p) p2 attr(p2, "size") plot_autosize(p1)
Plot a numeric vector as a histogram with theme_this and thisplot palettes.
plot_histogram( data, binwidth = 0.01, show_border = FALSE, border_color = "black", alpha = 1, palette = "viridis", palcolor = NULL, xlab = "Value", ylab = "Count", legend.position = "right", theme_use = "theme_this", theme_args = list() )plot_histogram( data, binwidth = 0.01, show_border = FALSE, border_color = "black", alpha = 1, palette = "viridis", palcolor = NULL, xlab = "Value", ylab = "Count", legend.position = "right", theme_use = "theme_this", theme_args = list() )
data |
A numeric vector. |
binwidth |
Width of the bins. |
show_border |
Whether to show bin borders. |
border_color |
Color of the bin borders. |
alpha |
Transparency of the bins. |
palette |
Palette name used to fill bins by count. See show_palettes. |
palcolor |
Custom colors used to create a color palette. |
xlab, ylab
|
Axis titles. |
legend.position |
Legend position. |
theme_use |
Theme function applied to the plot. |
theme_args |
A named list of arguments passed to |
A ggplot object.
set.seed(1) plot_histogram(rnorm(500), binwidth = 0.2)set.seed(1) plot_histogram(rnorm(500), binwidth = 0.2)
Plot two- or three-column data as a scatter plot with theme_this and
thisplot palettes. Optional smoothing, correlation annotation, point density,
and marginal plots are available.
plot_scatter( data, smoothing_method = c("lm", "loess"), palette = "Chinese", palcolor = NULL, title = NULL, xlab = NULL, ylab = NULL, legend.title = NULL, legend.position = "right", theme_use = "theme_this", theme_args = list(), margins = c("both", "x", "y"), marginal_type = NULL, margins_size = 10, compute_correlation = TRUE, compute_correlation_method = c("pearson", "spearman"), keep_aspect_ratio = TRUE, facet = FALSE, se = FALSE, pointdensity = TRUE )plot_scatter( data, smoothing_method = c("lm", "loess"), palette = "Chinese", palcolor = NULL, title = NULL, xlab = NULL, ylab = NULL, legend.title = NULL, legend.position = "right", theme_use = "theme_this", theme_args = list(), margins = c("both", "x", "y"), marginal_type = NULL, margins_size = 10, compute_correlation = TRUE, compute_correlation_method = c("pearson", "spearman"), keep_aspect_ratio = TRUE, facet = FALSE, se = FALSE, pointdensity = TRUE )
data |
A data frame with 2 columns ( |
smoothing_method |
Smoothing method passed to ggplot2::geom_smooth.
Can be |
palette |
Palette name used for groups or point-density coloring. See show_palettes. |
palcolor |
Custom colors used to create a color palette. |
title, xlab, ylab
|
Plot titles. |
legend.title |
Legend title. |
legend.position |
Legend position. |
theme_use |
Theme function applied to the plot. |
theme_args |
A named list of arguments passed to |
margins, marginal_type, margins_size
|
Marginal plot controls used when
|
compute_correlation |
Whether to annotate Pearson or Spearman correlation. |
compute_correlation_method |
Correlation method: |
keep_aspect_ratio |
Whether to use a 1:1 aspect ratio. |
facet |
Whether to facet by the grouping column when |
se |
Whether to show smoothing uncertainty. |
pointdensity |
Whether to color ungrouped points by local density when
|
A ggplot object, or a ggExtra grob when marginal plots are added.
set.seed(1) plot_scatter(data.frame(x = rnorm(80), y = rnorm(80))) plot_scatter( data.frame( x = rnorm(80), y = rnorm(80), cluster = rep(c("A", "B"), each = 40) ) )set.seed(1) plot_scatter(data.frame(x = rnorm(80), y = rnorm(80))) plot_scatter( data.frame( x = rnorm(80), y = rnorm(80), cluster = rep(c("A", "B"), each = 40) ) )
Prints a data frame as an aligned console table with ANSI colors. By default each column receives one distinct color from 'palette'; set 'by = "row"' to use one color per row. Custom 'color_by' specifications can still color individual values. Column widths are computed from visible ANSI text, so escape sequences and Chinese text do not break alignment in the console. Colors are emitted only when the output supports ANSI colors (a terminal or RStudio, or when 'options(thisplot.colors = TRUE)' is set); captured output stays clean.
print_colored_table( x, color_by = NULL, colors = NULL, palette = "Chinese", by = "col", ... )print_colored_table( x, color_by = NULL, colors = NULL, palette = "Chinese", by = "col", ... )
x |
A data frame. |
color_by |
A character vector of column names to color, or a named list of color sources. If 'NULL' (default), colors are assigned according to 'by'. |
colors |
Optional color source used for all 'color_by' columns unless overridden by a named list in 'color_by': a named hex vector whose names match the values of the colored columns, a plain hex vector recycled per row, or 'NA' to fall back to 'palette'. |
palette |
Palette name passed to 'palette_colors()' for default row or column colors, or columns without explicit colors. |
by |
Whether default palette colors are assigned by '"col"' (default) or '"row"'. |
... |
Additional arguments passed to 'format()'. |
'x' invisibly.
t1 <- data.frame( name = c("a", "b", "c"), col1 = c(1L, 2L, 3L), col2 = c(4L, 5L, 6L) ) print_colored_table(t1)t1 <- data.frame( name = c("a", "b", "c"), col1 = c(1L, 2L, 3L), col2 = c(4L, 5L, 6L) ) print_colored_table(t1)
ChineseColors objectPrint ChineseColors object
## S3 method for class 'ChineseColors' print(x, ...)## S3 method for class 'ChineseColors' print(x, ...)
x |
A |
... |
Additional arguments. |
Details of the ChineseColors object.
Print colors object
## S3 method for class 'colors' print(x, ...)## S3 method for class 'colors' print(x, ...)
x |
A colors object (data frame with color information). |
... |
Additional arguments passed to print. |
Details of the colors objec.
Print logo
## S3 method for class 'thisplot_logo' print(x, ...)## S3 method for class 'thisplot_logo' print(x, ...)
x |
Input information. |
... |
Other parameters. |
Print the ASCII logo
Rasterise the layers of a plot
rasterise_plot( plot, layers = c("Point", "Tile", "Path", "Line", "Segment"), dpi = 300, dev = "ragg", recurse = TRUE )rasterise_plot( plot, layers = c("Point", "Tile", "Path", "Line", "Segment"), dpi = 300, dev = "ragg", recurse = TRUE )
plot |
A |
layers |
Layer types to rasterise, named without the |
dpi |
Resolution of the rasterised layers, in dots per inch.
Default is |
dev |
Graphic device used to render the rasterised layers, passed to
|
recurse |
Whether to rasterise the sub-plots of a |
The plot object with its heavy layers rasterised. Objects that are
neither a ggplot nor a patchwork are returned unchanged, with a warning.
panel <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() + ggplot2::facet_wrap(~cyl) rasterise_plot(panel) rasterise_plot(patchwork::wrap_plots(panel, panel), dpi = 150)panel <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() + ggplot2::facet_wrap(~cyl) rasterise_plot(panel) rasterise_plot(patchwork::wrap_plots(panel, panel), dpi = 150)
Convert an RGBA (Red, Green, Blue, Alpha) color to RGB by compositing it with a background color based on the alpha channel.
RGBA2RGB(RGBA, BackGround = c(1, 1, 1))RGBA2RGB(RGBA, BackGround = c(1, 1, 1))
RGBA |
A list containing RGB values and alpha channel. |
BackGround |
The background RGB color to composite with.
Default is |
A numeric vector of RGB values.
This function takes a data frame representing segments in a plot and shortens and offsets them based on the provided arguments.
segements_df(data, shorten_start, shorten_end, offset)segements_df(data, shorten_start, shorten_end, offset)
data |
A data frame containing the segments. It should have columns 'x', 'y', 'xend', and 'yend' representing the start and end points of each segment. |
shorten_start |
The amount to shorten the start of each segment by. |
shorten_end |
The amount to shorten the end of each segment by. |
offset |
The amount to offset each segment by. |
The modified data frame with the shortened and offset segments.
library(ggplot2) temp_nodes <- data.frame( "x" = c(10, 40), "y" = c(10, 30) ) data <- data.frame( "x" = c(10, 40), "y" = c(10, 30), "xend" = c(40, 10), "yend" = c(30, 10) ) ggplot(temp_nodes, aes(x = x, y = y)) + geom_point(size = 12) + xlim(0, 50) + ylim(0, 50) + geom_segment( data = data, aes(x = x, xend = xend, y = y, yend = yend) ) ggplot(temp_nodes, aes(x = x, y = y)) + geom_point(size = 12) + xlim(0, 50) + ylim(0, 50) + geom_segment( data = segements_df( data, shorten_start = 2, shorten_end = 3, offset = 1 ), aes(x = x, xend = xend, y = y, yend = yend) )library(ggplot2) temp_nodes <- data.frame( "x" = c(10, 40), "y" = c(10, 30) ) data <- data.frame( "x" = c(10, 40), "y" = c(10, 30), "xend" = c(40, 10), "yend" = c(30, 10) ) ggplot(temp_nodes, aes(x = x, y = y)) + geom_point(size = 12) + xlim(0, 50) + ylim(0, 50) + geom_segment( data = data, aes(x = x, xend = xend, y = y, yend = yend) ) ggplot(temp_nodes, aes(x = x, y = y)) + geom_point(size = 12) + xlim(0, 50) + ylim(0, 50) + geom_segment( data = segements_df( data, shorten_start = 2, shorten_end = 3, offset = 1 ), aes(x = x, xend = xend, y = y, yend = yend) )
This function displays color palettes using ggplot2.
show_palettes( palettes = NULL, type = c("discrete", "continuous"), index = NULL, palette_names = NULL, return_names = TRUE, return_palettes = FALSE )show_palettes( palettes = NULL, type = c("discrete", "continuous"), index = NULL, palette_names = NULL, return_names = TRUE, return_palettes = FALSE )
palettes |
A list of color palettes.
Default is |
type |
The type of palettes to include.
Default is |
index |
The indices of the palettes to include.
Default is |
palette_names |
The names of the palettes to include.
Default is |
return_names |
Whether to return the names of the selected palettes.
Default is |
return_palettes |
Whether to return the colors of selected palettes.
Default is |
If return_palettes is TRUE, returns a list of color palettes. If return_names is TRUE (default), returns a character vector of palette names. Otherwise, returns NULL (called for side effects to display the plot).
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", "Chinese" ), return_palettes = TRUE ) # Include Chinese palettes via prefix show_palettes( palette_names = c("ChineseRed", "ChineseBlue"), return_palettes = TRUE )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", "Chinese" ), return_palettes = TRUE ) # Include Chinese palettes via prefix show_palettes( palette_names = c("ChineseRed", "ChineseBlue"), return_palettes = TRUE )
Simple random color selection
simple_colors(n = 10, palette = NULL)simple_colors(n = 10, palette = NULL)
n |
The number of colors to return. Default is |
palette |
The name of the palette to use.
Default is |
A character vector of hexadecimal color codes.
simple_colors() show_palettes(simple_colors(n = 5)) # Get colors from a specific palette simple_colors(n = 10, palette = "Paired") simple_colors(n = 10, palette = "ChineseBlue") simple_colors(n = 10, palette = "Spectral")simple_colors() show_palettes(simple_colors(n = 5)) # Get colors from a specific palette simple_colors(n = 10, palette = "Paired") simple_colors(n = 10, palette = "ChineseBlue") simple_colors(n = 10, palette = "Spectral")
Remove unused columns from the data in a ggplot or patchwork object. This function keeps only the columns that are actually used in the plot (e.g., in mappings, aesthetics, or facets), which can significantly reduce the object size when the original data contains many unused columns.
slim_data(p) ## S3 method for class 'ggplot' slim_data(p) ## S3 method for class 'patchwork' slim_data(p)slim_data(p) ## S3 method for class 'ggplot' slim_data(p) ## S3 method for class 'patchwork' slim_data(p)
p |
A |
A ggplot or patchwork object with unused data columns removed.
library(ggplot2) p <- ggplot( data = mtcars, aes(x = mpg, y = wt, colour = cyl) ) + geom_point() object.size(p) colnames(p$data) p_slim <- slim_data(p) object.size(p_slim) colnames(p_slim$data)library(ggplot2) p <- ggplot( data = mtcars, aes(x = mpg, y = wt, colour = cyl) ) + geom_point() object.size(p) colnames(p$data) p_slim <- slim_data(p) object.size(p_slim) colnames(p_slim$data)
Standardize each row of a data matrix by subtracting the mean and dividing by the standard deviation.
standardise(data)standardise(data)
data |
A matrix or data frame to standardize. |
The standardized data with the same structure as input.
Visualizes data using various plot types such as bar plots, rose plots, ring plots, pie charts, trend plots, area plots, dot plots, sankey plots, chord plots, venn diagrams, and upset plots.
StatPlot( meta.data, stat.by, group.by = NULL, split.by = NULL, bg.by = NULL, flip = FALSE, NA_color = "grey", NA_stat = TRUE, keep_empty = FALSE, individual = FALSE, stat_level = NULL, plot_type = c("bar", "rose", "ring", "pie", "trend", "trend_alluvial", "area", "dot", "sankey", "chord", "venn", "upset"), venn_engine = c("ggVennDiagram", "venny"), venn_args = list(), stat_type = c("percent", "count", "value"), value.by = NULL, top_n = Inf, rank.by = c("absolute", "value"), complete_groups = NULL, value_cutoff = NULL, value_limits = NULL, value_midpoint = 0, value_legend_title = NULL, bar_fill = NULL, bar_width = 0.8, point_size = c(2.5, 7), character_width = 50, return_data = FALSE, position = c("stack", "dodge"), palette = "Chinese", palcolor = NULL, alpha = 1, bg_palette = "Chinese", bg_palcolor = NULL, bg_alpha = 0.2, label = FALSE, label_cutoff = NULL, label.size = 3.5, label.fg = "black", label.bg = "white", label.bg.r = 0.1, aspect.ratio = NULL, title = NULL, subtitle = NULL, xlab = NULL, ylab = NULL, legend.position = "right", legend.direction = "vertical", theme_use = "theme_this", theme_args = list(), x_text_angle = 45, grid_major = TRUE, grid_major_colour = "grey80", grid_major_linetype = 2, grid_major_linewidth = 0.3, combine = TRUE, nrow = NULL, ncol = NULL, byrow = TRUE, force = FALSE, seed = 11 )StatPlot( meta.data, stat.by, group.by = NULL, split.by = NULL, bg.by = NULL, flip = FALSE, NA_color = "grey", NA_stat = TRUE, keep_empty = FALSE, individual = FALSE, stat_level = NULL, plot_type = c("bar", "rose", "ring", "pie", "trend", "trend_alluvial", "area", "dot", "sankey", "chord", "venn", "upset"), venn_engine = c("ggVennDiagram", "venny"), venn_args = list(), stat_type = c("percent", "count", "value"), value.by = NULL, top_n = Inf, rank.by = c("absolute", "value"), complete_groups = NULL, value_cutoff = NULL, value_limits = NULL, value_midpoint = 0, value_legend_title = NULL, bar_fill = NULL, bar_width = 0.8, point_size = c(2.5, 7), character_width = 50, return_data = FALSE, position = c("stack", "dodge"), palette = "Chinese", palcolor = NULL, alpha = 1, bg_palette = "Chinese", bg_palcolor = NULL, bg_alpha = 0.2, label = FALSE, label_cutoff = NULL, label.size = 3.5, label.fg = "black", label.bg = "white", label.bg.r = 0.1, aspect.ratio = NULL, title = NULL, subtitle = NULL, xlab = NULL, ylab = NULL, legend.position = "right", legend.direction = "vertical", theme_use = "theme_this", theme_args = list(), x_text_angle = 45, grid_major = TRUE, grid_major_colour = "grey80", grid_major_linetype = 2, grid_major_linewidth = 0.3, combine = TRUE, nrow = NULL, ncol = NULL, byrow = TRUE, force = FALSE, seed = 11 )
meta.data |
The data frame containing the data to be plotted. |
stat.by |
The column name(s) in |
group.by |
The column name(s) in |
split.by |
The column name in |
bg.by |
The column name in |
flip |
Whether to flip the plot.
Default is |
NA_color |
The color to use for missing values. |
NA_stat |
Whether to include missing values in the plot.
Default is |
keep_empty |
Whether to keep empty groups in the plot.
Default is |
individual |
Whether to plot individual groups separately.
Default is |
stat_level |
The level(s) of the variable(s) specified in |
plot_type |
The type of plot to create.
Can be one of |
venn_engine |
The engine used when |
venn_args |
A list of additional arguments passed to
|
stat_type |
The type of statistic to compute for the plot.
Can be one of |
value.by |
Numeric column used when |
top_n |
Maximum number of records retained per group and split in value
mode. Default is |
rank.by |
Rank continuous values by absolute magnitude or signed value. |
complete_groups |
For value dot plots, retain every available group for a label selected in any group within the same split. |
value_cutoff |
Optional minimum absolute value. |
value_limits |
Optional continuous colour limits. Symmetric limits are inferred by default. |
value_midpoint |
Midpoint of the continuous colour scale. |
value_legend_title |
Legend title for continuous values. |
bar_fill |
Optional fixed fill used by value bars. |
bar_width |
Width of bars in value mode. |
point_size |
Size range for value dot plots. |
character_width |
Maximum wrapped label width in value mode. |
return_data |
Return the plot and prepared data in value mode. |
position |
The position adjustment for the plot.
Can be one of |
palette |
The name of the color palette to use.
Default is |
palcolor |
Custom colors to use instead of palette.
Default is |
alpha |
The transparency level for the plot. |
bg_palette |
The name of the background color palette to use for bar plots. |
bg_palcolor |
The color to use in the background color palette. |
bg_alpha |
The transparency level for the background color in bar plots. |
label |
Whether to add labels on the plot.
Default is |
label_cutoff |
Optional minimum plotted value required to show a label.
Labels are shown only for values strictly greater than this cutoff. For
percentage plots, use proportions; for example, |
label.size |
The size of the labels. |
label.fg |
The foreground color of the labels. |
label.bg |
The background color of the labels. |
label.bg.r |
The radius of the rounded corners of the label background. |
aspect.ratio |
Aspect ratio of the panel. Default is |
title |
The title of the plot.
Default is |
subtitle |
The subtitle of the plot.
Default is |
xlab |
The label for the x-axis.
Default is |
ylab |
The label for the y-axis.
Default is |
legend.position |
The position of the legend.
Can be one of |
legend.direction |
The direction of the legend.
Can be one of |
theme_use |
The theme to use for the plot.
Default is |
theme_args |
Additional arguments to pass to the theme function.
Default is |
x_text_angle |
Rotation angle for x-axis labels.
Default is |
grid_major |
Whether to show major panel grid lines.
Default is |
grid_major_colour |
Color of major panel grid lines. |
grid_major_linetype |
Linetype of major panel grid lines. |
grid_major_linewidth |
Line width of major panel grid lines. |
combine |
Whether to combine multiple plots into one.
Default is |
nrow |
Number of rows when combining plots.
Default is |
ncol |
Number of columns when combining plots.
Default is |
byrow |
Whether to fill plots by row when combining.
Default is |
force |
Whether to force plotting even when variables have more than 100 levels.
Default is |
seed |
Random seed for reproducibility.
Default is |
set.seed(1) meta_data <- data.frame( Type = factor( sample(c("A", "B", "C"), 50, replace = TRUE, prob = c(0.5, 0.3, 0.2) ) ), Group = factor(sample(c("X", "Y", "Z"), 50, replace = TRUE)), Batch = factor(sample(c("B1", "B2"), 50, replace = TRUE)) ) meta_data$Region <- factor( ifelse(meta_data$Group %in% c("X", "Y"), "R1", "R2"), levels = c("R1", "R2") ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", split.by = "Batch", plot_type = "bar", position = "dodge" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", stat_type = "count", plot_type = "ring", position = "dodge" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", stat_type = "count" ) StatPlot( meta_data, stat.by = "Type", plot_type = "pie" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", stat_type = "count", plot_type = "area" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", plot_type = "dot" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", stat_type = "count", plot_type = "trend" ) rank_data <- data.frame( Feature = paste0("Feature", 1:12), Group = rep(c("Control", "Treatment"), each = 6), Value = c( -2.4, 1.8, 1.2, -0.8, 0.6, 0.2, 2.7, -2.1, 1.5, 0.9, -0.5, 0.3 ) ) StatPlot( rank_data, stat.by = "Feature", value.by = "Value", group.by = "Group", stat_type = "value", plot_type = "bar", top_n = 4, flip = TRUE, palette = "RdBu" ) StatPlot( rank_data, stat.by = "Feature", value.by = "Value", group.by = "Group", stat_type = "value", plot_type = "dot", top_n = 3, palette = "RdBu" ) importance_data <- data.frame( Variable = paste0("Variable", 1:8), Importance = c(0.91, 0.78, 0.64, 0.52, 0.43, 0.31, 0.18, 0.09) ) StatPlot( importance_data, stat.by = "Variable", value.by = "Importance", stat_type = "value", top_n = 5, flip = TRUE, bar_fill = "#3C8DBC" )set.seed(1) meta_data <- data.frame( Type = factor( sample(c("A", "B", "C"), 50, replace = TRUE, prob = c(0.5, 0.3, 0.2) ) ), Group = factor(sample(c("X", "Y", "Z"), 50, replace = TRUE)), Batch = factor(sample(c("B1", "B2"), 50, replace = TRUE)) ) meta_data$Region <- factor( ifelse(meta_data$Group %in% c("X", "Y"), "R1", "R2"), levels = c("R1", "R2") ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", split.by = "Batch", plot_type = "bar", position = "dodge" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", stat_type = "count", plot_type = "ring", position = "dodge" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", stat_type = "count" ) StatPlot( meta_data, stat.by = "Type", plot_type = "pie" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", stat_type = "count", plot_type = "area" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", plot_type = "dot" ) StatPlot( meta_data, stat.by = "Type", group.by = "Group", stat_type = "count", plot_type = "trend" ) rank_data <- data.frame( Feature = paste0("Feature", 1:12), Group = rep(c("Control", "Treatment"), each = 6), Value = c( -2.4, 1.8, 1.2, -0.8, 0.6, 0.2, 2.7, -2.1, 1.5, 0.9, -0.5, 0.3 ) ) StatPlot( rank_data, stat.by = "Feature", value.by = "Value", group.by = "Group", stat_type = "value", plot_type = "bar", top_n = 4, flip = TRUE, palette = "RdBu" ) StatPlot( rank_data, stat.by = "Feature", value.by = "Value", group.by = "Group", stat_type = "value", plot_type = "dot", top_n = 3, palette = "RdBu" ) importance_data <- data.frame( Variable = paste0("Variable", 1:8), Importance = c(0.91, 0.78, 0.64, 0.52, 0.43, 0.31, 0.18, 0.09) ) StatPlot( importance_data, stat.by = "Variable", value.by = "Importance", stat_type = "value", top_n = 5, flip = TRUE, bar_fill = "#3C8DBC" )
This function creates a theme with all elements blank except for axis lines and labels. It can optionally add coordinate axes in the plot.
theme_blank( add_coord = TRUE, xlen_npc = 0.15, ylen_npc = 0.15, xlab = "", ylab = "", lab_size = 12, ... )theme_blank( add_coord = TRUE, xlen_npc = 0.15, ylen_npc = 0.15, xlab = "", ylab = "", lab_size = 12, ... )
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 |
The label of the x-axis. |
ylab |
The label of the y-axis. |
lab_size |
The size of the axis labels. |
... |
Arguments passed to the ggplot2::theme. |
A list containing ggplot2 theme objects and annotation objects.
If add_coord is TRUE, returns a list with coordinate arrows;
otherwise returns a list with theme only.
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)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)
Minimal themes for sankey, alluvial and sankey bump plots
theme_sankey( base_size = 11, base_family = "", base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_alluvial( base_size = 11, base_family = "", base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_sankey_bump( base_size = 11, base_family = "", base_line_size = base_size/22, base_rect_size = base_size/22 )theme_sankey( base_size = 11, base_family = "", base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_alluvial( base_size = 11, base_family = "", base_line_size = base_size/22, base_rect_size = base_size/22 ) theme_sankey_bump( base_size = 11, base_family = "", base_line_size = base_size/22, base_rect_size = base_size/22 )
base_size |
Base font size, given in pts. |
base_family |
Base font family. |
base_line_size |
Base size for line elements. |
base_rect_size |
Base size for rect elements. |
The default theme for scop plot function.
theme_this(aspect.ratio = NULL, base_size = 12, ...)theme_this(aspect.ratio = NULL, base_size = 12, ...)
aspect.ratio |
Aspect ratio of the panel. |
base_size |
Base font size |
... |
Arguments passed to the ggplot2::theme. |
A ggplot2 theme object (class theme, gg).
library(ggplot2) p <- ggplot( data = mtcars, aes(x = wt, y = mpg, colour = factor(cyl)) ) + geom_point() p + theme_this()library(ggplot2) p <- ggplot( data = mtcars, aes(x = wt, y = mpg, colour = factor(cyl)) ) + geom_point() p + theme_this()
The thisplot logo, using ASCII or Unicode characters Use cli::ansi_strip to get rid of the colors.
thisplot_logo(unicode = cli::is_utf8_output())thisplot_logo(unicode = cli::is_utf8_output())
unicode |
Unicode symbols on UTF-8 platforms. Default is cli::is_utf8_output. |
A character vector with class thisplot_logo.
https://github.com/tidyverse/tidyverse/blob/main/R/logo.R
thisplot_logo()thisplot_logo()
Convert proportions to percentages
to_percent(x)to_percent(x)
x |
A numeric vector. |
A numeric vector expressed as percentages.
to_percent(c(1, 1, 2)) to_percent(c(0, 0))to_percent(c(1, 1, 2)) to_percent(c(0, 0))
Display a grid of color swatches with optional names or color codes.
visual_colors( colors, names = NULL, num_per_row = 30, title = NULL, label_mode = c("auto", "chinese", "pinyin", "rgb", "hex") )visual_colors( colors, names = NULL, num_per_row = 30, title = NULL, label_mode = c("auto", "chinese", "pinyin", "rgb", "hex") )
colors |
A character vector of hex color codes. |
names |
Optional. A character vector of names for each color.
Default is |
num_per_row |
Number of colors per row.
Default is |
title |
Optional title for the visualization.
Default is |
label_mode |
Label layout mode. Default is |
An HTML widget.
# Visualize a simple color palette visual_colors( colors = c("#FF0000", "#00FF00", "#0000FF"), names = c("Red", "Green", "Blue") ) visual_colors( colors = c("#FF0000", "#00FF00"), names = c("(255, 0, 0)", "(0, 255, 0)") ) visual_colors(thisplot::palette_list$Paired) # Use with ChineseColors cc <- ChineseColors() visual_colors( colors = cc$blue[1:60], title = "Chinese Blue Colors" )# Visualize a simple color palette visual_colors( colors = c("#FF0000", "#00FF00", "#0000FF"), names = c("Red", "Green", "Blue") ) visual_colors( colors = c("#FF0000", "#00FF00"), names = c("(255, 0, 0)", "(0, 255, 0)") ) visual_colors(thisplot::palette_list$Paired) # Use with ChineseColors cc <- ChineseColors() visual_colors( colors = cc$blue[1:60], title = "Chinese Blue Colors" )