Home > Software engineering >  How to fix problem with "for" in the ggplot2 label
How to fix problem with "for" in the ggplot2 label

Time:12-25

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?

CodePudding user response:

Some thoughts:

I think, that for in this case is recognized something like a function, command or operator.

And R waits for something a la: for == bla-bla, for(bla-bla) etc...

How to solve:

I tried to fix this problem with latin unicode f o r characters. But it didn't help.

But we have Cyrillic Small Letter O, ha-ha. And it helps! ;)

Your modified code:

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)~f\U043Er~trend', 6), pvalue)), 
              parse = TRUE, size = 7)
p

Output: enter image description here

CodePudding user response:

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

  • Related