0

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.

0

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

The issue seems to be device dependent. Using ragg png device, this looks correct.
@teunbrand Great, thanks! I've updated the answer where I use ragg in ggsave.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.