Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Created May 7, 2020 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonocarroll/536d738aab013212ab48a9b5509b2ee8 to your computer and use it in GitHub Desktop.
Save jonocarroll/536d738aab013212ab48a9b5509b2ee8 to your computer and use it in GitHub Desktop.
Add a fake legend annotation to a ggplot
library(ggplot2)
library(dplyr)
## fake data
d <- mtcars %>%
group_by(cyl) %>%
summarise(lower = min(disp),
med = median(disp),
upper = max(disp))
p <- ggplot(d, aes(x = factor(cyl), y = med)) +
geom_pointrange(aes(ymin = lower, ymax = upper)) +
geom_point(aes(factor(cyl), lower)) +
geom_point(aes(factor(cyl), upper))
## configure legend
config <- tibble::tribble(
~ x, ~ y, ~ s, ~ t,
1, 1, 1, "Min",
3, 1, 2, "Median",
6, 1, 1, "Max"
)
lcol <- "forestgreen"
adj <- 0.1
## build fake legend
legend <- ggplot(config, aes(x, y)) +
geom_point(aes(size = s), show.legend = FALSE, col = lcol) +
scale_size_continuous(range = c(2, 4)) +
coord_cartesian(ylim = c(1 - adj, 1 + adj)) +
geom_text(aes(y = y - 0.5 * adj, label = t), size = 6, col = lcol) +
geom_line(lwd = 2, col = lcol) +
theme_void()
legend
## combine
p +
theme(plot.margin = unit(c(5.5, 5.5, 100, 5.5), "points")) +
annotation_custom(
ggplotGrob(legend),
xmin = 1,
xmax = 3,
ymin = -50,
ymax = 40
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment