Thomas Yee
Thomas Yee

Reputation: 31

knitr plotting code chunks to be seen and run

I've been trying to solve the following problem using knitr. In \LaTeX I wish to define a chunk (once) called myplot. Then I want to say something such as:

The code

<<myplot, tidy = FALSE>>=
plot(runif(9), runif(9),
     xlab = "x",
     ylab = "y",)
@

results in Figure~\ref{fig:myownlabel}.

\begin{figure}[hh]
\begin{center}
<<myplotfig, out.width='.50\\linewidth', width=6.6, height=4.8, echo=FALSE>>=
par(las = 1, mfrow = c(1, 1), mar = c(5, 4, 1, 1)+0.1)
<<myplot>>
@
\caption{
I insist to have the caption in \LaTeX.
\label{fig:myownlabel}
}
\end{center}
\end{figure}

I know how to do it in Sweave but cannot seem to do it in knitr. That is, the code chunk is seen by the reader. Can you give me any suggestions? Thanks in advance. Thomas

Upvotes: 3

Views: 730

Answers (1)

Yihui Xie
Yihui Xie

Reputation: 30174

This is one difference between knitr and Sweave: Sweave does not keep plots by default (unless you specify fig=TRUE), but knitr does (unless you really do not want them, using fig.keep='none').

<<myplot, tidy = FALSE, fig.keep = 'none'>>=
plot(runif(9), runif(9),
     xlab = "x",
     ylab = "y",)
@

\begin{figure}[hh]
\begin{center}
<<myplotfig, out.width='.50\\linewidth', fig.width=6.6, fig.height=4.8, echo=FALSE>>=
par(las = 1, mfrow = c(1, 1), mar = c(5, 4, 1, 1)+0.1)
<<myplot>>
@
\caption{
I insist to have the caption in \LaTeX.
\label{fig:myownlabel}
}
\end{center}
\end{figure}

Although the problem has been solved so far, I have a few other comments:

  1. when you use knitr (>= 1.1), you should be able to see a warning about the syntax of your code chunks, and you are required to call Sweave2knitr() to fix the problems; you will realize width and height are not valid chunk options in knitr (use fig.width and fig.height); see here for more information
  2. for the chunk myplot, I would use eval=FALSE because you probably do not want to evaluate the code twice;
  3. with knitr, you can actually do everything through chunk options, e.g.

    <<myplot, tidy=FALSE, eval=FALSE, echo=-1>>=
    @
    <<myplot, out.width='.5\\linewidth', fig.width=6.6, fig.height=4.8, fig.align='center', echo=FALSE, fig.pos='hh', fig.cap='I insist to have the caption in \\LaTeX.'>>=
    par(las = 1, mfrow = c(1, 1), mar = c(5, 4, 1, 1)+0.1)
    plot(runif(9), runif(9),
         xlab = "x",
         ylab = "y",)
    @
    

    this gives you both the center and figure environments, and produces a label fig:myplot automatically.

Upvotes: 4

Related Questions