R latex2exp TeX() greek letter display error

Viewed 355

I have a problem with latex2exp TeX() function. I have no idea why \beta doesn't work here. As you can see in the figure attached, only blank square appears. Any help would be greatly appreciated. Thank you.

ggplot(data=B, aes(x=b1)) +
  geom_histogram(
    aes(y=..density..),
    binwidth = .005) +
  coord_cartesian(xlim=c(-1.1,1.1)) +
  xlab(TeX(r'(distribution of $\beta_1$)')) +
  geom_vline(xintercept = 1,color="blue") +
  geom_vline(xintercept = -1,color="blue")

corresponding plot

enter image description here

2 Answers

You can do this using expression:

library(ggplot2)


ggplot(mtcars, aes(mpg)) +
  geom_histogram(
    aes(y=..density..),
    binwidth = 1) +
  xlab(expression(distribution~of~beta[1]))

Created on 2021-04-19 by the reprex package (v2.0.0)

If you need to use latex2exp::tex(), note that backslashes have special meaning to R and need to be escaped with another backslash, i.e. you need '$\\beta_1$.

Your call to xlab() thus could be

xlab(latex2exp::TeX("distribution of $\\beta_1$"))
Related