How to add labels to plot with facets?

Hi all, I'm working with a data frame like this:

food_totals <- tibble::tribble(
  ~ food, ~ year, ~ total, ~ overall_change,
  "Orange", 2012, 5, -3,
  "Orange", 2013, 3, -3,
  "Orange", 2014, 2, -3,
  "Kiwi", 2012, 4, 2,
  "Kiwi", 2013, 5, 2,
  "Kiwi", 2014, 6, 2,
  "Eggplant", 2012, 4, -4,
  "Eggplant", 2013, 2, -4,
  "Eggplant", 2014, 0, -4
)

I want to create a set of line charts to show the change over time for each, which is easy enough.

food_totals %>% 
           ggplot(aes(year, total)) + 
  geom_line(aes(colour = food, group = food)) + 
  facet_wrap(vars(food)) + 
  theme(axis.text.x = element_text(angle = 90))

The problem I'm having is that I want to include an annotation on each of the charts that shows the value in that food's "overall_change" column. Whenever I try to insert overall_change as a label, I'm told that the object overall_change cannot be found.

Thank you for your time!

Hi @juliannek,

You can play around with the aesthetics but here is one approach:

library(tidyverse)

food_totals <- tibble::tribble(
  ~ food, ~ year, ~ total, ~ overall_change,
  "Orange", 2012, 5, -3,
  "Orange", 2013, 3, -3,
  "Orange", 2014, 2, -3,
  "Kiwi", 2012, 4, 2,
  "Kiwi", 2013, 5, 2,
  "Kiwi", 2014, 6, 2,
  "Eggplant", 2012, 4, -4,
  "Eggplant", 2013, 2, -4,
  "Eggplant", 2014, 0, -4
)

label_data <- 
  food_totals %>% 
  group_by(food) %>% 
  slice_max(year)

food_totals %>% 
  ggplot(aes(year, total)) + 
  geom_line(aes(colour = food, group = food)) + 
  geom_label(aes(year, total, label = overall_change),
             data = label_data) +
  facet_wrap(vars(food)) + 
  theme(axis.text.x = element_text(angle = 90))

1 Like

Thank you very much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.