julien
julien

Reputation: 113

Knitr: combination of chunk options so a figure is not output but the code is + single figure file output

I am writing Beamer slides in Rnw using knitr. (Used to use Sweave but I just realised code looks much better in knitr.)

I like to output my figures in pdf and include them on separate slides (I have an environment that makes them completely fill a slide). Only problem: I cannot seem to find if there is a combination of chunk options that would allow me show the code but not the figure.

MWE below.

\documentclass[aspectratio=169]{beamer}

<<set-options,echo=FALSE,warning=FALSE,message=FALSE>>=
# Load required libraries
require(knitr)
# Knitr options
opts_chunk$set(echo = TRUE, 
               warning = FALSE, 
               message = FALSE, 
               fig.width = 6, 
               fig.height = 4,
               fig.keep = FALSE)
@

\begin{document}
%%
\begin{frame}[fragile]\frametitle{Frame 1}
<<test-plot-1>>=
x = 1:100
plot(x, sin(x))
@
\end{frame}
%%
\begin{frame}[fragile]\frametitle{Frame 2}
<<test-plot-2,include=FALSE>>=
plot(x, sin(x))
@
\end{frame}
%%
\begin{frame}\frametitle{Frame 3}
\includegraphics{\Sexpr{fig_chunk('test-plot-2', 'pdf')}}
\end{frame}
\end{document}

Tried a variety of combinations.. Frame 2 is always empty, whereas I would like to see the code there.

Actually, side question: is there a way to force the generation of a single figure file for a chunk? If instead of my current first chunk, I use

<<test-plot-1>>=
x = 1:100
plot(x, sin(x))
abline(h=0)
@

then I get two pdf files, test-plot-1-1.pdf and test-plot-1-2.pdf. I understand the logic (I could be making multiple plots in a chunk, in particular when "reserving" my files as I do), but it is a little frustrating to try to remember how many instructions I have issued in a plot.

Upvotes: 0

Views: 28

Answers (0)

Related Questions