Currently, using TeX()
with ggplot2 to plot formatted text is markedly different from base graphics. With base graphics, calling
text(TeX(r"($\alpha + \beta$)"))
will plot the expression in the current plot.
In ggplot, the following will work:
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point() +
xlab(TeX(r"(Car \textbf{weight})")) +
ylab(TeX(r"(Car \textbf{fuel efficiency})")) # use the return value of TeX directly
but in the geoms like geom_text
, geom_label
, and annotate
that take a label
aesthetic, the input vector for the label
aesthetic is expected to be of type character
, rather than of type expression
. In order to plot formatted text and formulas, the user is expected to pass a character representation of the plotmath expression and use the parameter parse=TRUE
:
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
annotate("text", x = 4, y = 25, label = "alpha+beta", parse=TRUE)
(note that in some cases, the geom will accept an expression, but will throw a warning).
The only way to use TeX in these situations is to make it return a character value and set parse
to TRUE, e.g.:
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
annotate("text", x = 4, y = 25, label = TeX(r"(\alpha+\beta)", parse=TRUE)
I propose to add the functions: geom_text_tex
, geom_label_tex
, and annotate_tex
. These functions will forward to the underlying ggplot functions, and set the appropriate parameters for the user, such that:
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
annotate_tex(x = 4, y = 25, label = r"(\alpha+\beta)")
will automatically parse TeX, turn it into an expression, and forward it to annotate
with parse=TRUE
.