Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knitr plotting code chunks to be seen and run

Tags:

r

knitr

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

like image 890
Thomas Yee Avatar asked Feb 13 '26 05:02

Thomas Yee


1 Answers

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.

like image 167
Yihui Xie Avatar answered Feb 15 '26 17:02

Yihui Xie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!