How to annotate() ggplot with latex

RGgplot2

R Problem Overview


I'd like to add latex text to a ggplot2 plot using annotate(). Using expression(), as described here for adding latex to axis labels, does not seem to work. To wit:

# Use expression() to create subscripted text
p <- ggplot(mpg, aes(x=cty, y=hwy)) + geom_point() +
  scale_x_continuous(expression(text[subscript])) 

# But expression() in annotate adds nothing to the plot
p + annotate("text", x=10, y=40, label=expression(text[subscript])) 

# Passing regular text to annotate works fine
p + annotate("text", x=10, y=40, label="foo") 

Why are expressions treated differently by annotate than by other ggplot functions? And how can I annotate with latex?

R Solutions


Solution 1 - R

There is an R package called latex2exp which may be helpful. It has function TeX which accepts some LaTeX expressions enclosed with dollar sign $ as in this example:

library(latex2exp)
library(ggplot2)

qplot(1, "A")+
     ylab(TeX("Formula: $\\frac{2hc^2}{\\lambda^\\beta}$"))+
     xlab(TeX("$\\alpha$"))

Example

More examples can be found in this vignette.

Solution 2 - R

You can use the parse argument, without expression:

p + annotate("text", x=10, y=40, label="text[subscript]", parse=TRUE)

Solution 3 - R

The tikzDevice package is back on CRAN (latest version 0.9 published Nov 2015).

Using tikz does require a full LaTeX installation; it may be easiest to do via knitr within a LaTeX document (just set dev="tikz" in the chunk options). However, you can use it to create a standalone figure as well. Ironically, the hardest part of this question was getting a text subscript, which requires an additional LaTeX package (fixltx2e) for the \textsubscript command ...

library(tikzDevice)
## add a package to the defaults
options(tikzLatexPackages=
            c(getOption("tikzLatexPackages"),"\\usepackage{fixltx2e}"))
tikz("tikz.tex",standAlone=TRUE)
library("ggplot2"); theme_set(theme_bw())
p <- ggplot(mpg, aes(x=cty, y=hwy)) + geom_point() +
  scale_x_continuous(name="text\\textsubscript{subscript}")
p + annotate("text", x=10, y=40, label="text\\textsubscript{subscript}")
dev.off()

system("pdflatex tikz.tex")

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrew SteenView Question on Stackoverflow
Solution 1 - RGegznaVView Answer on Stackoverflow
Solution 2 - RMatthew PlourdeView Answer on Stackoverflow
Solution 3 - RBen BolkerView Answer on Stackoverflow