latex2exp icon indicating copy to clipboard operation
latex2exp copied to clipboard

Error in using TeX inside geom_text()

Open caijun opened this issue 6 years ago • 3 comments

I would like to annotate math formulas on the plot using geom_text() and I specified the TeX expression to the label argument in following code.

library(ggplot2)
library(latex2exp)

p <- ggplot(mtcars, aes(mpg, cyl)) + 
  geom_point() + 
  geom_text(aes(x = 30, y = 7, label = TeX("$\\theta$ = 270")))
print(p)

However, it produces following error

Don't know how to automatically pick scale for object of type expression. Defaulting to continuous.
Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  cannot coerce class ‘"expression"’ to a data.frame

caijun avatar May 04 '18 18:05 caijun

This can be resolved by specifying the output of TeX() as character, although "character" is not one of the values that the output argument can take, and turning the parse argument in geom_text() to TRUE. Like following code,

library(ggplot2)
library(latex2exp)

p <- ggplot(mtcars, aes(mpg, cyl)) + 
  geom_point() + 
  # labs(title = TeX("$\\theta$ = 270"))
  geom_text(aes(x = 30, y = 7, label = TeX("$\\theta$ = 270", output = "character")), 
            parse = TRUE)
print(p)

caijun avatar May 05 '18 09:05 caijun

This appears to be a new issue (for me) related to some change in ggplot2. The workaround above worked for me as documented. See stackoverflow question below. Thanks.

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

dalewsteele avatar Jun 21 '18 11:06 dalewsteele

#12 is fixed as of 0.9.0. I will add a note about ggplot in the documentation.

stefano-meschiari avatar Jan 24 '22 23:01 stefano-meschiari