62

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?

Community
  • 1
  • 1
Drew Steen
  • 16,045
  • 12
  • 62
  • 90

3 Answers3

70

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.

Community
  • 1
  • 1
GegznaV
  • 4,938
  • 4
  • 23
  • 43
  • 16
    Your example works for labels, but the question was about annotate. Your example isn't working in an annotate layer for me, but, if you specify output='character' and add 'parse=TRUE' to the annotate call it does. `annotate(geom='text', x=3, y=3, label=Tex("$\\hat{Y} = B_0 + B_1X_1", output='character'), parse=TRUE)` – svannoy Dec 02 '16 at 22:18
  • Hi do you know how to add italic style on the text? – Jiaxiang Aug 02 '18 at 08:12
  • @Jiaxiang are you familiar with [this thread](https://stackoverflow.com/questions/25732949/italic-greek-letters-in-r-plot) – GegznaV Aug 02 '18 at 14:55
  • @Vilmantas Gegzna Yes, I read it before. What I want is to make the `Tex()` output in the italic style. I try `Tex(italic('...'))`, but it fails. – Jiaxiang Aug 03 '18 at 05:54
  • I skimmed through the [latex2exp vignette](ftp://cran.r-project.org/pub/R/web/packages/latex2exp/vignettes/using-latex2exp.html) but did not notice anything about italic style. You may try looking look through more carefully. I'm not sure if **latex2exp** support italic style. – GegznaV Aug 03 '18 at 15:53
29

You can use the parse argument, without expression:

p + annotate("text", x=10, y=40, label="text[subscript]", parse=TRUE)
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
  • Could you confirm for me whether you get any unusual behavior if you try using `label=expression(text[subscript]), parse = TRUE)`? (I haven't upgraded to 0.9.2 yet...) – joran Sep 20 '12 at 14:36
  • Ok...still a little groggy this morning, and I did that by mistake first time through. Never seen that sort of response from R before. Weird. – joran Sep 20 '12 at 14:41
  • First time I've seen that as well. It lets you correct the label argument with whatever you type after the '?'. – Matthew Plourde Sep 20 '12 at 14:44
  • @Joran's comment - I saw ?, and then R Studio crashed (Max OSX 10.7.4, R 2.14.1, RStudio 0.96.330, ggplot2 0.9.1). – Drew Steen Sep 20 '12 at 15:02
  • the option `parse = TRUE` makes it interpreted as `plotmath` annotation-like mathematical expression – 千木郷 Jan 20 '19 at 19:34
17

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

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • 1
    Great answer. Takes a little while to compile, producing a bunch of warnings like ``Measuring dimensions of: \char77``, but it's my preferred solution when unicode lets me down (see https://stackoverflow.com/questions/27690729/greek-letters-symbols-and-line-breaks-inside-a-ggplot-legend-label) – PatrickT Mar 28 '18 at 10:46
  • This is an awesome answer @BenBolker, I managed to adapt it to my own graph, but I am still struggling with adjusting the size (height and length) of the printed pdf file, any advice? – Álvaro A. Gutiérrez-Vargas May 22 '21 at 19:32
  • 1
    not offhand. There should be something in the `tikz` options to let you deal with this, I would think? If you can't figure it out I would say that posting a new question would be very sensible – Ben Bolker May 22 '21 at 19:46
  • As you pointed out, the solution is to use `width` and `height` options inside the `tikz()` function. For example, in you answer it should be something like the following `tikz("tikz.tex",standAlone=TRUE, height=1, width=1.5 )`. Thank you a lot @BenBolker, you saved the day (as always!). – Álvaro A. Gutiérrez-Vargas May 23 '21 at 09:49