Annotate a plot made with ggplot2 with an equation using latex2exp::TeX

大兔子大兔子 提交于 2019-12-11 17:32:14

问题


My goal is to annotate a plot made with ggplot2 by placing an equation in white space within the plot using the package latex2exp

For example, given the equation:

eqn <- "$\\textbf{Volume}(ml) = 0.035 \\cdot \\textbf{CSA}(mm^2) + 0.127 \\cdot \\textbf{age}(months) - 7.8$"

Running the following code in R 3.5:

library(ggplot2)
library(latex2exp)

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() + 
  annotate("text", x = 4, y = 40, label=TeX(eqn), hjust=0, size = 5)

My example code fails with the error below:

Error in stats::complete.cases(df[, vars, drop = FALSE]) : 
  invalid 'type' (expression) of argument

What am I doing wrong?


回答1:


A working solution, based on:

https://github.com/stefano-meschiari/latex2exp/issues/13

ggplot(mpg, aes(x = displ, y = hwy)) +
  geom_point() + 
  annotate("text", x=3, y=40, label=TeX(eqn, output="character"),
           hjust=0, size = 4, parse = TRUE)



来源:https://stackoverflow.com/questions/50957441/annotate-a-plot-made-with-ggplot2-with-an-equation-using-latex2exptex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!