typestar

Labels and annotation in R

Titles, captions, and pointing at the one observation that matters.

library(ggplot2)
library(dplyr)

runs <- tibble(day = 1:6, tpm = c(88, 92, 96, 99, 104, 101))
best <- slice_max(runs, tpm, n = 1)

plot <- ggplot(runs, aes(day, tpm)) +
  geom_line() +
  geom_point() +
  geom_text(aes(label = tpm), vjust = -0.8, size = 3) +
  annotate("segment", x = best$day, xend = best$day, y = 80, yend = best$tpm,
           linetype = "dashed", colour = "gray50") +
  annotate("label", x = best$day, y = 82, label = "best run", size = 3) +
  labs(title = "Six sessions", subtitle = "tokens per minute",
       caption = "typestar.io", x = "session", y = NULL) +
  ylim(80, 110)

print(length(plot$layers))
ggsave(tempfile(fileext = ".png"), plot, width = 5, height = 3, dpi = 100)

How it works

  1. labs sets every text element in one call.
  2. annotate draws a single mark, not a mapped layer.
  3. geom_text maps a label column onto the data.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
671
Tokens
216
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 123 seconds.

Type this snippet

Step 1 of 3 in Finishing a plot, step 12 of 15 in ggplot2.

← Previous Next →