This function adds labels at the median position of each group to a ggplot
object. Labels can be added either as plain text or as label boxes, with
optional repelling to avoid overlaps (using the
ggprepel package if installed).
Arguments
- p
A ggplot object with mapping and data (
ggplot).- labels
Column name (unquoted) indicating the group label to display.
- color
Color of the label text (
character). Default is"black".- repel
Logical. If
TRUE(default), overlapping labels are repelled using theggprepelpackage.- label.box
Logical. If
TRUEit uses a boxed label (geom_label) instead of plain text (geom_text). Default isFALSE.- size
Size of the label text (
numeric). Default is2.- ...
Additional arguments passed to the corresponding underlying geom:
ggplot2::geom_text()(repel=FALSEandlabel.box=FALSE)ggplot2::geom_label()(repel=FALSEandlabel.box=TRUE)ggrepel::geom_text_repel()(repel=TRUEandlabel.box=FALSE)ggrepel::geom_label_repel()(repel=TRUEandlabel.box=TRUE)
Value
A ggplot2 layer (geom_text,
geom_label,
geom_text_repel, or
geom_label_repel).
Details
The function summarizes the data by computing the median x and y positions for each label group.
If repel = TRUE, it uses
geom_text_repel() (label.box = FALSE)
or geom_label_repel() (label.box =
TRUE).
If repel = FALSE, it uses geom_text() (label.box
= FALSE) or geom_label() (label.box = TRUE).
If repel = TRUE, the ggprepel package must be
installed.
Examples
if (FALSE) { # \dontrun{
library(ggplot2)
library(ggrepel)
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = as.factor(cyl))) +
geom_point()
p2 <- add_labels(
p,
labels = cyl,
repel = TRUE,
label.box = FALSE,
size = 5,
min.segment.length = 0
)
p2
p3 <- add_labels(
p,
labels = cyl,
repel = TRUE,
label.box = TRUE,
size = 3,
box.padding = 1
)
p3
p4 <- add_labels(
p,
labels = cyl,
repel = FALSE,
label.box = TRUE,
size = 4,
)
p4
} # }
