# NOT RUN {
library(ggrepel)
library(gginnards)
random_string <- function(len = 6) {
paste(sample(letters, len, replace = TRUE), collapse = "")
}
# Make random data.
set.seed(1001)
d <- tibble::tibble(
x = rnorm(100),
y = rnorm(100),
group = rep(c("A", "B"), c(50, 50)),
lab = replicate(100, { random_string() })
)
# using defaults
ggplot(data = d, aes(x, y, label = lab)) +
geom_point() +
stat_dens1d_labels()
# using defaults
ggplot(data = d, aes(x, y, label = lab)) +
geom_point() +
stat_dens1d_labels(geom = "text_repel")
# if no mapping to label is found, it is set row names
ggplot(data = d, aes(x, y)) +
geom_point() +
stat_dens1d_labels(geom = "text_repel")
# using defaults, along y-axis
ggplot(data = d, aes(x, y, label = lab)) +
geom_point() +
stat_dens1d_labels(orientation = "y", geom = "text_repel")
# example labelling with coordiantes
ggplot(data = d, aes(x, y, label = sprintf("x = %.2f\ny = %.2f", x, y))) +
geom_point() +
stat_dens1d_filter(colour = "red") +
stat_dens1d_labels(geom = "text_repel", colour = "red", size = 3)
# Using geom_debug() we can see that all 100 rows in \code{d} are
# returned. But only those labelled in the previous example still contain
# the original labels.
ggplot(data = d, aes(x, y, label = lab)) +
geom_point() +
stat_dens1d_labels(geom = "debug")
ggplot(data = d, aes(x, y, label = lab, colour = group)) +
geom_point() +
stat_dens1d_labels(geom = "text_repel")
ggplot(data = d, aes(x, y, label = lab, colour = group)) +
geom_point() +
stat_dens1d_labels(geom = "text_repel", label.fill = NA)
# we keep labels starting with "a" across the whole plot, but all in sparse
# regions. To achieve this we pass as argument to label.fill a fucntion
# instead of a character string.
label.fun <- function(x) {ifelse(grepl("^a", x), x, "")}
ggplot(data = d, aes(x, y, label = lab, colour = group)) +
geom_point() +
stat_dens1d_labels(geom = "text_repel", label.fill = label.fun)
# }
Run the code above in your browser using DataLab