Helena
Helena

Reputation: 21

math notation on ggplot2 axis labels

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

Upvotes: 2

Views: 2029

Answers (1)

Amar
Amar

Reputation: 1373

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") 

Upvotes: 2

Related Questions