Search code examples
rggplot2annotationsfacet-wrap

How to add different annotations on figures with facet_wrap


I would like to add different annotations on figures produced by facet_wrap.

I tried the below code, but the it showed error such as "Error in FUN(X[[i]], ...) : object 'value' not found".

dat_text <- data.frame(
  label = c("TRUE:FALSE = 686:324", "TRUE:FALSE = 976:34", "TRUE:FALSE = 516:494", "TRUE:FALSE = 360:650",
            "TRUE:FALSE = 351:659", "TRUE:FALSE = 440:570", "TRUE:FALSE = 645:365", "TRUE:FALSE = 151:859", "TRUE:FALSE = 542:468"),
  cyl   = c(Agricultural_land, Artificial_land, Precipitation, Protected_area,
            RiverLake, Seashore, Temperature, Volcanic_area, Wasteland)
)


z_cor <- fit01_zsize2 %>%
  ggplot(aes(x = value_without, y = value_with, color = value))+
  geom_point(shape = 1)+
   geom_text(
     data    = dat_text,
     mapping = aes(x = -Inf, y = -Inf, label = label),
     hjust   = -0.1,
     vjust   = -1
   )+
  geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
  scale_color_manual(values = c("TRUE" = "salmon", "FALSE" = "steelblue"))+
  facet_wrap(.~variable1)+
  theme(strip.text.x = element_text(size = 20),
            axis.title=element_text(size=16))

plot(z_cor)

When I tried the same code without geom_text(), it worked.


When I could avoid the error, the new problem has come. I pasted the figure I created. Many annotations has come in a figure. enter image description here


Solution

  • As @stefan noted, your text layer's data should reference the faceting variable:

    ggplot(mtcars, aes(wt, mpg)) +
      geom_point() +
      facet_wrap(~am) +
      geom_text(data = data.frame(wt = 2, mpg = c(30, 12), am = c(0,1),
                                  label = c("one note", "and another")),
                aes(label = label))
    

    enter image description here