Dr. Yutam
Dr. Yutam

Reputation: 89

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.

Upvotes: 0

Views: 612

Answers (2)

AndrewGB
AndrewGB

Reputation: 16836

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

Upvotes: 0

stefan
stefan

Reputation: 123783

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)

Upvotes: 1

Related Questions