legend_bracket: Add legend with brackets to a ggplot object

View source: R/ggplot_integration.R

legend_bracketR Documentation

Add legend with brackets to a ggplot object

Description

This function allows you to add a custom legend with brackets using the + operator, similar to ggplot2 layers.

Usage

legend_bracket(
  labels,
  colors,
  comparisons = NULL,
  x = NULL,
  y = NULL,
  width = NULL,
  height = NULL,
  unit = "npc",
  position = "topleft",
  title = NULL,
  text_size = 10,
  text_family = "sans",
  text_face = "plain",
  title_size = 11,
  title_face = "bold",
  sig_size = 11,
  sig_face = "plain",
  output_width = NULL,
  output_height = NULL,
  bracket_margin = NULL,
  legend_x = NULL,
  legend_y = NULL
)

Arguments

labels

Character vector of group names (in order)

colors

Character vector of colors matching the groups

comparisons

Data frame with columns: group1, group2, label

x

Numeric. X position of legend (0-1 scale or with unit)

y

Numeric. Y position of legend (0-1 scale or with unit)

width

Numeric. Width of legend box (default NULL = auto)

height

Numeric. Height of legend box (default NULL = auto)

unit

Character. Unit for width and height: "npc" (0-1 scale), "in", "cm", "mm" (default "npc")

position

Character. Preset position: "topleft", "topright", "bottomleft", "bottomright", or NULL for manual x/y

title

Character. Legend title (optional)

text_size

Numeric. Font size for labels (default 10)

text_family

Character. Font family (default "sans")

text_face

Character. Font face (default "plain")

title_size

Numeric. Title font size (default 11)

title_face

Character. Title font face (default "bold")

sig_size

Numeric. Significance symbol size (default 11)

sig_face

Character. Significance symbol face (default "plain")

output_width

Numeric. Output figure width in inches (for accurate bracket positioning)

output_height

Numeric. Output figure height in inches (for accurate bracket positioning)

bracket_margin

Numeric. Custom horizontal spacing between legend text and brackets (default NULL = auto-adaptive)

legend_x

Numeric. Custom X position for legend box (0-1 scale, overrides adaptive positioning)

legend_y

Numeric. Custom Y position for legend box (0-1 scale, overrides adaptive positioning)

Value

A vbracket_legend object

Examples


library(ggplot2)
data <- data.frame(x = 1:10, y = 1:10, group = rep(c("A", "B"), each = 5))
labels <- c("A", "B")
colors <- c("A" = "red", "B" = "blue")
comparisons <- add_bracket_comparisons(groups1 = "A", groups2 = "B", labels = "*")

p <- ggplot(data, aes(x, y, color = group)) + geom_point() +
  legend_bracket(labels, colors, comparisons,
                 position = "topleft",
                 output_width = 6, output_height = 4)

# Then use regular ggsave with same dimensions
ggsave(file.path(tempdir(), "plot.pdf"), p, width = 6, height = 4)


vbracket documentation built on Jan. 7, 2026, 9:06 a.m.