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.
CodePudding user response:
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)
CodePudding user response:
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")