1

I've seen similar questions posted on this and using \u00B1 has worked in the past but now this does not work anymore.

avg1<- c(expression(paste("22.2 ","\u00B1", " 0.83")))
avg2<- c(expression(paste("22.9 ","%+-%", " 0.67")))

density2 <- ggplot(Success_all, aes(x=Temp, fill = shape)) +
  geom_density(aes(y=..density..),alpha=0.4) +
  annotate(geom = "text", x = 21.85, y= 0.5, label= avg1, parse=TRUE, size=3, color = "aquamarine3")+
  annotate(geom = "text", x = 22.55, y= 0.6, label= avg2, parse=TRUE, size=3, color = "firebrick4") +
  annotate(geom = "text", x = 20, y= 0.65, label= "(C)", size=4, fontface="bold") +
  theme_bw() +
  scale_fill_manual(values = c("firebrick4", "aquamarine3")) +
  scale_x_continuous(breaks = seq(20,25,0.5)) +
  theme(panel.grid =element_blank(), 
        legend.title = element_blank()) +
  xlab("Temperature (C)") +
  ylab("Density") +
  geom_vline(xintercept = 22.86774, color = "firebrick4", linetype = 3) +
  geom_vline(xintercept = 22.17358, color = "aquamarine3", linetype = 3)

(https://i.stack.imgur.com/RcZpi.png)

Not sure why neither works. I tried inputting "\pm" as well but just got an error for the backslash so it wouldn't execute.

stefan
  • 90,330
  • 6
  • 25
  • 51
  • 2
    You can just use `paste("22.2 ","\u00B1", " 0.83")` with the unicode bits, i.e. without the `expression()`. – teunbrand Jul 14 '22 at 13:16
  • Without data it's hard to tell, I have tried `label = expression(22.2 ~ "\u00B1" ~ 0.83)` and it worked *even without `parse=TRUE`*. – Rui Barradas Jul 14 '22 at 13:55

1 Answers1

0

The reason is the wrong use of 1) quotes and 2) the %+-% operator - see also Ben Bolker's answer to a very related thread.

library(ggplot2)

avg1 <- paste("22.2", "\u00B1", "0.83")
## needs format x%+-%y and change the paste position
avg2 <- paste(expression(22.9 %+-% 0.67))

ggplot(data.frame()) +
## no "expression" needed, but then also no parse = TRUE
  annotate(geom = "text", x = 1, y = 1, label = avg1) +
  annotate(geom = "text", x = 1, y = 2, label = list(avg2), parse = TRUE) 

Created on 2022-07-14 by the reprex package (v2.0.1)

P.S.: I'm adding the expression as a list in order to avoid a warning

tjebo
  • 21,977
  • 7
  • 58
  • 94