68

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?

4
  • you might take a look at the tikzDevice package ... Commented Sep 20, 2012 at 14:21
  • Seems to be no longer actively maintained. (But still potentially useful!) Commented Sep 20, 2012 at 14:24
  • 1
    My understanding is that it's still pretty widely used, and functional, but in a current state of orphanage due to stricter CRAN/R CMD check rules ... it was last modified on R-forge 15 July 2012 ... Commented Sep 20, 2012 at 14:27
  • 1
    PS: current development status at groups.google.com/forum/#!topic/tikzdevice/73Hd2Eln3Qk Commented Sep 20, 2012 at 14:50

3 Answers 3

76

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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)
Hi do you know how to add italic style on the text?
@Jiaxiang are you familiar with this thread
@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.
I skimmed through the latex2exp vignette 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.
29

You can use the parse argument, without expression:

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

5 Comments

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...)
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.
First time I've seen that as well. It lets you correct the label argument with whatever you type after the '?'.
@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).
the option parse = TRUE makes it interpreted as plotmath annotation-like mathematical expression
18

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

4 Comments

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 stackoverflow.com/questions/27690729/…)
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?
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
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!).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.