I am trying to produce a document using Sweave or Knitr which contains plots.
Here is a minimal example for Sweave:
\documentclass{article}
\title{Plot example}
\begin{document}
\maketitle
<<setup>>=
library("graphics")
myplot = function(n) {
plot(cumsum(rnorm(n)),type="l",main="The stock market",ylab="Money",xlab="Time")
}
@
This is what the stock market looks like over the past month:
\begin{center}
<<fig=T,echo=F,width=10,height=4>>=
myplot(10)
@
\end{center}
and over the past decade:
\begin{center}
<<fig=T,echo=F,width=10,height=4>>=
myplot(1000)
@
\end{center}
\end{document}
The Knitr version has slightly different chunk headers:
<<echo=F,fig.width=10,fig.height=4>>=
The output looks like this:
In both cases, the width and height of the plots are hard-coded in the source file. This seems to me like bad software design. I would prefer to specify the width and height of the plots within the function myplot()
. Otherwise, if I want to change the way the plots look, or if I want to switch from letter paper to A4 paper, then I have the cumbersome task of changing several hard-coded width and height values using search and replace.
In Knitr, it is possible to change the default width and height through R code:
<<cache=FALSE>>=
opts_chunk$set(fig.width=3,fig.height=4);
@
However, this configuration must be separate from the code chunk in which the plot is executed, because Knitr (like Sweave) opens the plotting device before evaluating any of the chunk code. What I need is a way to specify the height and width within myplot()
.
What is an elegant way to specify the plot width and height together with the rest of the plot in Sweave or Knitr?