2

I want to add math notation to a ggplot2 axis using latex2exp, but I run into problems because scale_x_discrete() only accepts new label names when they are between quotation marks which renders the TeX() function, as used in the example below, as text. How can I both change the name of the labels while at the same time include math notation?

  p<-ggplot(data=x, aes(x=y, y=x)) +
  geom_errorbar(aes(ymin=x-ci, ymax=x+ci)) +
  scale_x_discrete(breaks=c("label1","label2"),
               labels=c("TeX('$\\alpha^\\beta$')","newlabel2")) 
  p

1 Answer 1

2

Checkout this vignette from the package creators:

https://cran.r-project.org/web/packages/latex2exp/vignettes/using-latex2exp.html

scale_color_discrete(labels=lapply(sprintf('$\\alpha = %d$', alpha), TeX))

For your code:

p<-ggplot(data=x, aes(x=y, y=x)) +
geom_errorbar(aes(ymin=x-ci, ymax=x+ci)) +
scale_x_discrete(breaks=c("label1","label2"),
               labels = lapply(sprintf('$\\alpha^\\beta$'), TeX)
p

The other option, if your math notation is not very complicated, is to use bquote and UTF codes:

mn <- bquote("\u03B1 \u03B2")
labels=c(mn, "newlabel2") 
Sign up to request clarification or add additional context in comments.

Comments

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.