Search code examples
rggplot2facet

Facets sort alphabetically when adding facet-specific annotions


I'm making a plot with several facets and want to specify the facet order like this:

library(tidyverse)

df <- tribble(
  ~year, ~country, ~value,
  2001, "France", 55, 
  2002, "France", 53, 
  2003, "France", 31, 
  2004, "France", 10, 
  2005, "France", 30, 
  2006, "France", 37, 
  2007, "France", 54, 
  2008, "France", 58, 
  2009, "France", 50, 
  2010, "France", 40, 
  2011, "France", 49, 
  2001, "USA", 55,
  2002, "USA", 53,
  2003, "USA", 64,
  2004, "USA", 40,
  2005, "USA", 30,
  2006, "USA", 39,
  2007, "USA", 55,
  2008, "USA", 53,
  2009, "USA", 71,
  2010, "USA", 44,
  2011, "USA", 40
) %>% 
  mutate(country = factor(country, c("USA", "France")))

ggplot(df, aes(year, value)) +
  geom_line() +
  facet_wrap(~country)

Which plots: enter image description here

So USA appears as a facet before France overriding the default alphabetical order.

Then I want to add some text to these facets and use different colors for this:

annot <- tribble(
  ~country, ~year, ~value, ~label,
  "France", 2004, 50, "Baguette",
  "USA", 2005, 50, "Hamburgers")

ggplot(df, aes(year, value)) +
  geom_line() +
  facet_wrap(~country) +
  geom_text(aes(label = label, x = year, y = value), 
            data = annot %>% filter(country == "France"),
            color = "red")  +
  geom_text(aes(label = label, x = year, y = value), 
            data = annot %>% filter(country == "USA"),
            color = "blue")

Which plots:

enter image description here

But now France is plotted before USA again! So I'm looking for a way to keep the original facet order I specified.


Solution

  • As @Axeman says. This (which is essentially repeating your code above) works as intended:

    annot <- tribble(
      ~country, ~year, ~value, ~label,
      "France", 2004, 50, "Baguette",
      "USA", 2005, 50, "Hamburgers") %>%
      mutate(country = factor(country, c("USA", "France")))