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 ggrepel
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 the ggrepel package.- label.box
Logical. If
TRUE
it 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:
geom_text()
(repel
=FALSE
andlabel.box
=FALSE
)geom_label()
(repel
=FALSE
andlabel.box
=TRUE
)geom_text_repel()
(repel
=TRUE
andlabel.box
=FALSE
)geom_label_repel()
(repel
=TRUE
andlabel.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 ggrepel::geom_text_repel()
(label.box = FALSE
) or ggrepel::geom_label_repel()
(label.box = TRUE
).
If repel = FALSE
, it uses ggplot2::geom_text()
(label.box
= FALSE
) or ggplot2::geom_label()
(label.box = TRUE
).
If repel = TRUE
, the ggrepel
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
} # }