Search code examples
rggplot2tidyverse

geom_text change factor order of facet plot


I am trying annotate individual plots of a facet plot. I have set the order to 2008, 1999 using factor levels. But when I add the geom_text to the ggplot, the order of the plots change. See examples below. What am I doing wrong? How can I solve this?

library(tidyverse)

df <- mpg %>% mutate(year = factor(year, levels = c(2008,1999)))

anno <- data.frame(xstar = c(5, 2), ystar = c(100, 70),
                   lab = c("text1","text2"),
                   year = c("2008","1999"))

df %>%  ggplot(aes(class, displ)) +
  geom_col(aes(fill=drv)) +
  facet_grid(~year) + 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  geom_text(data = anno, aes(x = xstar,  y = ystar, label = lab))

enter image description here


Solution

  • Convert the year column in your annotation dataframe also to a factor with the same levels and order as in your main df:

    library(ggplot2)
    
    df <- mpg
    df$year = factor(df$year, levels = c(2008, 1999))
    
    anno <- data.frame(
      xstar = c(5, 2), ystar = c(100, 70),
      lab = c("text1", "text2"),
      year = factor(c("2008", "1999"), levels = c(2008, 1999))
    )
    
    ggplot(df, aes(class, displ)) +
      geom_col(aes(fill = drv)) +
      geom_text(data = anno, aes(x = xstar, y = ystar, label = lab)) +
      facet_grid(~year) +
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))