71

I'm a newbie to both R and LaTeX and have just recently found how to plot a standard time series graph using R and save it as a png image. What I'm worried about is that saving it as an image and then embedding it into LaTeX is going to scale it and make it look ugly.

Is there a way to make R's plot() function output a vector graphic and embed that into LaTeX? I'm a total beginner in both so please be gentle :) Code snippets are highly appreciated!

agentofuser
  • 8,987
  • 11
  • 54
  • 85

4 Answers4

64

I would recommend the tikzDevice package for producing output for inclusion in LaTeX documents:

http://cran.r-project.org/web/packages/tikzDevice/index.html

The tikzDevice converts graphics produced in R to code that can be interpreted by the LaTeX package tikz. TikZ provides a very nice vector drawing system for LaTeX. Some good examples of TikZ output are located at:

http://www.texample.net/

The tikzDevice may be used like any other R graphics device:

require( tikzDevice )

tikz( 'myPlot.tex' )

plot( 1, 1, main = '\\LaTex\\ is $\\int e^{xy}$' )

dev.off()

Note that the backslashes in LaTeX macros must be doubled as R interprets a single backslash as an escape character. To use the plot in a LaTeX document, simply include it:

\include{path/to/myPlot.tex}

The pgfSweave package contains Sweave functionality that can handle the above step for you. Make sure that your document contains \usepackage{tikz} somewhere in the LaTeX preamble.

http://cran.r-project.org/

The advantages of tikz() function as compared to pdf() are:

  • The font of labels and captions in your figures always matches the font used in your LaTeX document. This provides a unified look to your document.

  • You have all the power of the LaTeX typesetter available for creating mathematical annotation and can use arbitrary LaTeX code in your figure text.

Disadvantages of the tikz() function are:

  • It does not scale well to handle plots with lots of components. These are things such as persp() plots of large matricies. The shear number of graphic elements can cause LaTeX to slow to a crawl or run out of memory.

  • The package is currently flagged as beta. This means that the interface or functionality of the package is subject to change if the authors find a compelling reason to do so.

I should end this post by disclaiming that I am an author of both the tikzDevice and pgfSweave packages so my opinion may be biased. However, I have used both packages to produce several academic reports in the last year and have been very satisfied with the results.

Sharpie
  • 17,323
  • 4
  • 44
  • 47
  • 3
    +1 Excellent post and very cool project you've got! I'll keep the pdf answer as "accepted" because it's easier on newcomers, but I'm trying out yours. Is there anything I need to specify on the LaTeX side besides the `include`? Got this error: `Environment tikzpicture undefined`. – agentofuser Dec 12 '09 at 15:53
  • Sorry, I should have made it more clear that you need to use the `tikz` package in your LaTeX document. Post edited. – Sharpie Dec 12 '09 at 18:26
  • Great package! For me, this was the first R package I installed and it took me a while to find out how to do this. For the next person: use the `install.packages()` command from within R - easy! @Sharpie, I would be interested in how to get the `R CMD install tikzDevice` command to work (I struggled with this for a while, 'with missing destination file operand' error) – Tom Jul 06 '11 at 09:19
  • @Tom `R CMD INSTALL` is a little misleading if you have used other package managers---you have to point it at a file that you downloaded yourself. Hence the `missing destination file`. To have the package downloaded for you, use `install.packages` from inside R. – Sharpie Jul 06 '11 at 19:49
  • @Sharpie, how does one go about centring the image in the resulting .tex file? – lightonphiri Sep 12 '12 at 16:18
  • 2
    It seems tikzDevice was [removed from the official CRAN repository](http://cran.r-project.org/web/packages/tikzDevice/index.html). I followed [this guide](http://lightonphiri.org/blog/r-graphical-representation-installing-tikzdevice-package) to install it. – saffsd Feb 15 '13 at 03:11
  • The guide mentioned by saffsd didn't work for me, but did put me on the right path. I was able to install tikzDevice via install.packages("tikzDevice", repos="http://cran.at.r-project.org/"). – Nathan Oct 13 '14 at 03:46
  • I had a lot of trouble and confusion initially because of tikzDevice errors. Solution: you already need the tikz TeX package installed when generating the plots in R, not only for the final LaTex process. – cbix Nov 09 '15 at 18:41
  • @obvio171 I honestly wouldn't call the `pdf` solution easier for newcomers - you replace the `pdf` command by `tikz` and the `\includegraphics` by `\include`, and that's it?! – Eike P. Jan 29 '16 at 10:58
  • Just did this and everything worked like a charm out of the box. Awesome! – Eike P. Jan 29 '16 at 10:59
  • @saffsd That's no longer true. Right now, the package is on CRAN. – Eike P. Jan 29 '16 at 10:59
  • Tip: use `\input{path/to/myPlot}` if you want to wrap the `tikzpicture` in `\resizebox` inside a `figure` environment since `\include{}` does a `\clearpage` before and after. – Richard Apr 20 '17 at 22:49
  • This example doesn't work because `\LaTex` is an undefined cs (it's `\LaTeX`, for the laymen). I can't fix it though because it would be too small a edit. – Arch Stanton Apr 23 '17 at 09:13
61

Shane is spot-on, you do want Sweave. Eventually.

As a newbie, you may better off separating task though. For that, do this:

  1. open a device: pdf("figures/myfile.pdf", height=6, width=6).
  2. plot your R object: plot(1:10, type='l', main='boring') -- and remember that lattice and ggplot need an explicit print around plot.
  3. important: close your device: dev.off() to finalize the file.
  4. optional: inspect the pdf file.
  5. in LaTeX, use usepackage{graphicx} in the document header, use
    \includegraphics[width=0.98\textwidth]{figures/myfile} to include the figure created earlier and note that file extension is optional.
  6. run this through pdflatex and enjoy.
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • 7
    I should also mention that separating the task as Dirk has done can be beneficial for very big documents: having to rebuild the entire document from scratch every time can be painful, not to mention the agony of debugging a big Sweave document. – Shane Dec 11 '09 at 20:06
  • 1
    There caching tricks and packages for that though. But yes, the takeaway is that the power of Sweave comes at a bit of a cost in terms of complexity and opaqueness. To put it mildly :) – Dirk Eddelbuettel Dec 11 '09 at 20:28
  • 1
    Thanks! You might update your answer with a few things I ran into so it's easier on other newbies like me that might come by: you have put `\usepackage{graphicx}` in the document header for this to run (found this here: http://tuxmann.blogspot.com/2006/06/latex-snippets-add-image-wrap-long.html); and you're missing a 'd' on `with=0.98` – agentofuser Dec 12 '09 at 15:50
  • Is there an alternative of `latex()` from `Hmisc` for plots? Ie something that prepares `\includegraphics` with an environment, "capture", etc. So to avoid writing this code manually. – Anton Tarasenko Dec 03 '13 at 08:48
  • Mixing in pdf did not work for me because I needed postscipt processing (pdf gave me a bounding box error). This may be a problem for someone else too. The solution turned out to be simple - get R to create .ps instead of .pdf: `postscript(file=myfile.ps,horizontal=FALSE)` – Willem Feb 22 '14 at 06:11
  • @DirkEddelbuettel - You mention this is a newbie approach... Out of interest, what would a 'pro' do differently? – n1k31t4 Mar 09 '16 at 20:02
23

You might want to consider using Sweave. There is a lot of great documentation available for this on the Sweave website (and elsewhere). It has very simple syntax: just put your R code between <<>>= and @.

Here's a simple example that ends up looking like this:

\documentclass[a4paper]{article}

\title{Sweave Example 1}
\author{Friedrich Leisch}

\begin{document}

\maketitle

In this example we embed parts of the examples from the
\texttt{kruskal.test} help page into a \LaTeX{} document:

<<>>=
data(airquality)
library(ctest)
kruskal.test(Ozone ~ Month, data = airquality)
@
which shows that the location parameter of the Ozone 
distribution varies significantly from month to month. Finally we
include a boxplot of the data:

\begin{center}
<<fig=TRUE,echo=FALSE>>=
boxplot(Ozone ~ Month, data = airquality)
@
\end{center}

\end{document}

To build the document, you can just call R CMD Sweave file.Rnw or run Sweave(file) from within R.

Yan Foto
  • 10,850
  • 6
  • 57
  • 88
Shane
  • 98,550
  • 35
  • 224
  • 217
  • 2
    I 2nd Sweave. I would only add that RStudio has wonderful integration with Sweave, which might be particularly important for a beginner (install a LaTeX distribution and click one button in RStudio). – Chris Beeley Apr 25 '12 at 20:54
  • @ChrisBeeley can you drop some link explaining RStudio and LaTeX integration? Thank you. – Wakan Tanka Jan 25 '16 at 23:08
  • http://rstudio-pubs-static.s3.amazonaws.com/639_b3a59601ba94400aabbe29025de83c10.html – Chris Beeley Jan 27 '16 at 07:07
  • I get no plot drawn such as [here](https://i.stack.imgur.com/V4FHA.png), why? Related question [here](http://tex.stackexchange.com/questions/340472/r-executable-code-in-latex) with broken MWE. – hhh Nov 22 '16 at 18:37
3

This is a dupe of a question on SO that I can't find.

But: http://r-forge.r-project.org/projects/tikzdevice/ -- tikz output from r and http://www.rforge.net/pgfSweave/ tikz code via sweave.

Using tikz will give you a look consistent with the rest of your document, plus it will use latex to typeset all the text in your graphs.

EDIT Getting LaTeX into R Plots

Community
  • 1
  • 1
Mica
  • 18,501
  • 6
  • 46
  • 43
  • 3
    That question is the opposite of this question: Here the OP is asking how to add R plots into a LaTeX document. There the OP was asking how to add LaTeX equations into an R plot. – Shane Dec 11 '09 at 21:52
  • 1
    The title was an intentional paraphrase :) – agentofuser Dec 11 '09 at 22:18
  • True enough, but isn't the answer the same ;) – Mica Dec 12 '09 at 00:08
  • Not quite, it is all a matter of the final product you are attempting to create. LaTex into R makes plots with LaTex elements while R into Latex creates laTex documents including R plots. – Francis Smart Jul 09 '14 at 12:33