# [R] Sweave with dev.new()

Marc Schwartz marc_schwartz at me.com
Tue Aug 10 14:27:45 CEST 2010

On Aug 10, 2010, at 3:51 AM, Gro Nilsen wrote:

> Dear list.
> I am preparing a R package, and the last step is to write a package
> vignette using Sweave. However, I am experiencing some trouble when trying
> to include plots in my Sweave document. That is, in my package I have made
> some plotting functions in which I start by calling 'new.dev()' to start a
> graphics device of a certain width and height, and then proceed with
> plot(). These functions work perfectly fine in R, and when I check and
> build my package with R CMD build/check.
>
> The problems start when I try to include the command and the output of my
> plotting functions in the Sweave document, and I suspect it must have
> something to do with the command 'dev.new()' in my code. Here is a basic
> example of a Sweave file which can hopefully illustrate the problem:
>
> \documentclass[a4paper]{article}
>
> \usepackage{Sweave}
> \RequirePackage{graphicx,fancyvrb}
>
>
> \title{Sweavetest}
>
> \begin{document}
>
> \section{Plotting}
>
> <<label=testfig,include=FALSE,echo=TRUE>>=
> dev.new(width=7,height=6,record=TRUE)
> plot(1:10,col="red")
> @
> \begin{figure}[ht]
> \begin{center}
> <<label=fig,fig=TRUE,echo=FALSE>>=
> <<testfig>>
> @
> \end{center}
> \caption{Testplot}
> \label{fig:test}
> \end{figure}
>
> \end{document}
>
>
> When I run Sweave on this file I get empty pdf and eps files named
> "Sweavetest-fig.pdf" and "Sweavetest-fig.eps", and the corresponding latex
> file is unable to create a PDF-file.
>
> Does anyone know what the problem is, and how I might solve it? This is
> the first time that I have worked with Sweave, so I might be missing
> something basic...
>
> Best regards,
> Gro Nilsen
> PhD-student, University of Oslo

It is not clear to me why you need the dev.new() call.  By default using Sweave, both PDF and EPS plot files will be created, for subsequent inclusion in the document as appropriate. Just define the plot dimensions in the figure chunk header:

<<label=fig,fig=TRUE,echo=FALSE,height=6,width=7>>=

Be aware however, that by default, the image size in the final document will be set to \textwidth * 0.8, irrespective of the dimensions that you have specified. You can alter that default behavior by using:

\usepackage[nogin]{Sweave}

in your document preamble. The figures will then be set to the sizes that you define in the figure chunk header.