Plot annotations with ggplot2

Data Visualisation with R

Annotation layer

  • As we saw before annotate() allows you to add elements to plots without a data.frame
map_data("world") |> 
  ggplot(aes(long, lat, group = group)) +
  geom_polygon(fill = "white", color = "black") +
  annotate("text", x = 0, y = 0, label = "Center", size = 10, color = "red")

Annotating a subset of data

  • We can add annotation by using a layer with a subset of data
map_data("world") |> 
  ggplot(aes(long, lat, group = group)) +
  geom_polygon(fill = "white", color = "black") +
  geom_polygon(fill = "#2babe2",
               data = ~filter(., region == "Australia"))

Text annotation

  • We use geom_text() or geom_label() to add text to a plot
ChickWeight |> 
  filter(Chick %in% unique(Chick)[1:5], .by = Diet) |> 
  ggplot(aes(x = Time, y = weight)) +
  geom_line(aes(group = Chick)) +
  geom_text(aes(label = paste("Chick", Chick)), nudge_x = 1,
            data = ~filter(., Time == max(Time), .by = Chick)) +
  facet_wrap(~Diet, labeller = label_both)

Text annotation with ggrepel

  • We can use the ggrepel package to avoid overlapping text
library(ggrepel)
ChickWeight |> 
  filter(Chick %in% unique(Chick)[1:5], .by = Diet) |> 
  ggplot(aes(x = Time, y = weight)) +
  geom_line(aes(group = Chick)) +
  geom_text_repel(aes(label = paste("Chick", Chick)), nudge_x = 1,
                  data = ~filter(., Time == max(Time), .by = Chick),
                  color = "red") +
  facet_wrap(~Diet, labeller = label_both)