Search code examples
rggplot2annotate

How to fix problem with "for" in the ggplot2 label


I'm trying to make a plot with facets and add annotations in each of the facets.

I want the annotations to look like "p for trend=0.001" like the plot such as this image.

enter image description here

The plot I made looks like the following:

enter image description here

ann_text <- data.frame(x = rep(5,6), y = rep(1,6),
                       conf.low = rep(5,6), conf.high = rep(5,6),
                       term = c('A', 'B', 'C', 'D', 'E', 'F'), 
                       pvalue = c("==0.04", "<0.001", "==0.999", "==0.999", "==0.99", "==0.99"))
ann_text$term <- factor(ann_text$term)


p <- ggplot(ann_text, aes(x = x, y = y)) +
  facet_wrap(.~term) +
    geom_text(data = ann_text, 
            aes(label=paste0(rep('italic(p)~fo~trend', 6), pvalue)), 
            parse = TRUE, size = 7)
p

I think I'm almost there, but "r" is missing in the annotation, because when I add "r", it raises the following error message.

Error in parse(text = text[[i]]) : <text>:1:14: unexpected '~'
1: italic(p)~for~
                 ^

How can I solve this problem?


Solution

  • Use double quotes inside the single-quoted expression to specify the character string you do not want interpreted as code. Incidentally, you do not need to use rep() because paste0() is vectorized and will apply the 'italic(p)~"for trend"' part to however many pvalue elements there are. So, like this:

    p <- ggplot(ann_text, aes(x = x, y = y)) +
      facet_wrap(.~term) +
        geom_text(data = ann_text, 
                aes(label=paste0('italic(p)~"for trend"', pvalue)), 
                parse = TRUE, size = 7)
    
    p