[R] Sweave figure aspect ratio

Duncan Murdoch murdoch at stats.uwo.ca
Sun Sep 9 15:23:12 CEST 2007


On 09/09/2007 7:24 AM, Werner Wernersen wrote:
> Hello,
> 
> using Sweave, is there any option to preserve the
> original aspect ratio of plots generated from R code?
> 
> Consider this Sweave chunk:
> <<test,echo=F,fig=T,width=2,height=2>>=
> x <- 1:10
> y <- sin(x)
> par(mar=c(4,4,0,4))
> plot(x,y,
>      xlab="x label",
>      ylab="y label"
>      )
> @
> 
> In Latex, I want to produce a plot of width 2 but
> don't care about the height. If I put the width and
> height like shown on the example, the box isn't square
> any more. But if I put only width or height in the
> Sweave option, then the values then the appearance is
> totally off. 
> 
> Is there any option for Sweave or other possibility to
> preserve the ratio of the sides of plots?

The width and height args in the header of the chunk are passed to the 
graphics device (postscript or pdf), but they don't appear in the LaTeX 
output.  To modify the appearance in LaTeX, you need to set a graphicx 
package parameter, e.g. something like

\setkeys{Gin}{width=2in}
<<test,echo=F,fig=T>>=
x <- 1:10
y <- sin(x)
par(mar=c(4,4,0,4))
plot(x,y,
      xlab="x label",
      ylab="y label"
      )
@

If you only specify width, then the aspect ratio will be maintained.

The \setkeys{} changes are persistent; as far as I know there's no way 
to say "go back to the default" afterwards.  So what I'd suggest is to 
define a macro (e.g. \Gwidth) to give the default width, and then call

\setkeys{Gin}{width=\Gwidth}

at the start of your document and after any change like the one above.

Duncan Murdoch



More information about the R-help mailing list