latex2exp
latex2exp copied to clipboard
Error in using TeX inside geom_text()
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
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)
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
#12 is fixed as of 0.9.0. I will add a note about ggplot in the documentation.