views:

1508

answers:

4

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!

+9  A: 

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.

Shane
+11  A: 

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{graphics} 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
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
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
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`
obvio171
Thanks for those corrections.
Dirk Eddelbuettel
+3  A: 

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 http://stackoverflow.com/questions/1395105/getting-latex-into-r-plots/1395553#1395553

Mica
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
The title was an intentional paraphrase :)
obvio171
True enough, but isn't the answer the same ;)
Mica
+9  A: 

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
+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`.
obvio171
Sorry, I should have made it more clear that you need to use the `tikz` package in your LaTeX document. Post edited.
Sharpie