Search code examples
rggplot2facetgeom-text

Cannot get geom_text labels with facet_wrap to work


I can't seem to figure out why this code isn't working for me. I am trying to add different geom_text labels to each facet of this graph. I've created a df for the annotation information.

Here is a sample of my dataset and code:

testParv <- data.frame(Stock = c("Birk","Dolly","Chil", "Pitt", "Birk","Dolly","Chil", "Pitt", "Birk","Dolly","Chil", "Pitt"), Parvicapsula = c("0", "1", "0", "1", "1", "0","0", "1", "0", "1", "1", "0"), Weight = c("19.2", "10.1", "5.2", "10.9", "20.5", "4.3", "15", "24", "6", "3", "8", "4.5"))

annotest <- data.frame(x1 = c(35, 35, 35, 35), y1 = c(0.4, 0.4, 0.4, 0.4), Stock = c("Birk", "Chil", "Dolly", "Pitt"), lab = c("p = 0.968", "p = 0.384", "p = 0.057", "p = 0.005"))

ggplot(data = testParv, aes(x = Weight, linetype = Parvicapsula)) +
  stat_ecdf() + 
  geom_text(data = annotest, aes(x = x1, y = y1, label = lab)) +
  theme_cowplot() + 
  facet_wrap(~Stock) + 
  ylab("ECDF") 

This produces an error: Error in FUN(X[[i]], ...) : object 'Parvicapsula' not found, but when I take out the geom_text() code it works fine.

Does anyone know why this doesn't work?

Many thanks, Julia


Solution

  • When you set the aes inside the ggplot() call those aesthetics will be used across all subsequent geoms. For example

    ggplot(mtcars, aes(hp, mpg)) + geom_point() + geom_line()
    

    In your case linetype from the first aes is being carried into geom_text. Several different ways to fix the error. Here are two options:

    # Move the data and aes calls into stat_ecdf 
    ggplot() +
      stat_ecdf(data = testParv, aes(x = Weight, linetype = Parvicapsula)) + 
      geom_text(data = annotest, aes(x = x1, y = y1, label = lab)) +
      theme_cowplot() + 
      facet_wrap(~Stock) + 
      ylab("ECDF") 
    
    # In geom_text overwrite the linetype with NA
    ggplot(data = testParv, aes(x = Weight, linetype = Parvicapsula)) +
      stat_ecdf() + 
      geom_text(data = annotest, aes(x = x1, y = y1, label = lab, linetype = NA)) +
      theme_cowplot() + 
      facet_wrap(~Stock) + 
      ylab("ECDF")