'How to add y bar in ggplot2() annotate?

I'm trying to add an annotation in my ggplot using annotate, but I was wondering if I can add the expression x bar (in latex it should be $\bar{x}$) in there.



Solution 1:[1]

Using ?plotmath and setting parse=TRUE you could do:

library(ggplot2)

ggplot(data.frame(x = 1, y = 1), aes(x, y)) +
  annotate(geom = "text", x = 1, y = 1, parse = TRUE, label ="bar(x)", size = 10)

Solution 2:[2]

Another option is to use unicode with bquote. However, when plotting directly in R, the bar may be slightly to the right (though this is probably device dependent). To get a high resolution image with the correct placement, you can use a combination of ggsave and ragg. Then, when the file is read back into R, it will plot correctly.

library(ggplot2)
library(magick)
library(ragg)

p <- ggplot(data.frame(x = 50, y = 25), aes(x, y)) +
  annotate(
    geom = "text",
    x = 50,
    y = 25,
    label = bquote("x\u0305") ,
    size = 10
  )

ggsave("agg_png-ggsave.png", p, device = agg_png)
ggs <- image_read("agg_png-ggsave.png")

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stefan
Solution 2