2

Goal

Put latex in x-axis text in ggplot2.

Data

Following is my sample data:

df <- structure(list(LV_type = c("LV Type: Car", "LV Type: Car", "LV Type: Car"
), reac_to_stpd_scn = c("Moving LV", "Moving LV", "Moving LV"
), Variable = c("AIC_AV_W_base", "AIC_AV_H_base", "AIC_TI_base"
), AIC = c(95.9878231314661, NA, 97.0658161329315), var_symbols = c("$\\dot{\\theta_{W}}$", 
"$\\dot{\\theta_{H}}$", "$\\tau^{-1}$")), row.names = c(NA, -3L
), class = c("tbl_df", "tbl", "data.frame"))

Attempts

library(ggplot2)
library(latex2exp)

Following obviously does not work:

ggplot(df) +
  geom_point(aes(var_symbols, AIC, color = Variable))

I also tried following:

ggplot(df) +
  geom_point(aes(Variable, AIC, color = Variable)) +
  scale_x_discrete(labels = c("AIC_AV_W_base" = expression("$\\dot{\\theta_{W}}$"),
                              "AIC_AV_H_base"   = expression("$\\dot{\\theta_{H}}$"),
                              "AIC_TI_base" = expression("$\\tau^{-1}$")))

enter image description here

I also tried to replace expression with latex2exp::TeX above, but that also did not work. Please suggest how can I put latex in axis labels.

1 Answer 1

2

As you have the expressions as a variable in your data frame, you can use them as the x aesthetic and pass the TeX() function to the label argument in scale_x_discrete().

library(latex2exp)
library(ggplot2)

 ggplot(df) +
  geom_point(aes(var_symbols, AIC, color = Variable)) +
  scale_x_discrete(labels = TeX) 

enter image description here

You can do the same thing with the legend if needed using scale_color_discrete().

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.