1
votes

I'm a little lost with the knitr package. I love the spin() function to quickly give me a global view of my analyses, but I need to save some very important plots in separate pdf (by example the 8th plot of my file should be save as "Figure1.pdf" AND displayed in the report).

When I write :

Some random code and plots...

pdf('Figure1.pdf')
plot(important plot)
dev.off()

Some random code and plots

The important plot is not displayed in the report after a spin(), and I would like to be in the report AND the pdf.

Is there any way ?

Thanks

2
I'm confused; surely when knitr compiles the document, it produces plots too, which should appear in the same directory (save embedded base64 encoded images). What output format are you using for the report?baptiste
to appear in the spun HTML knitr has to grab the output device and create a PNG which is then included in the HTML that spin creates. By starting a PDF device you've usurped that, so you don't get a PNG. I can't think how to generate both PDF and PNG without hooking into knitr's graphics at a low level, which might be possible.Spacedman
dev accepts a vector, so you can tell knitr to produce both pdf and png for any given chunkbaptiste
@Spacedman that's why I was asking for the output format; spin() can also produce pdf output, not just html, in which case there should be pdf files generated for each plot.baptiste

2 Answers

5
votes

spin() do save all plots, although it saves plots in the PNG format by default, because of the argument spin(..., format = 'Rmd') (R Markdown uses the PNG device).

You can specify chunk options in the R script as well: just use #+ or #-, e.g.

#' Some random code and plots...

#+ Figure1, fig.path='', dev=c('png', 'pdf')
plot(important plot)

#' Some random code and plots

Note the dev option takes a vector of devices, as @baptiste mentioned.

Or you use the Rnw format, e.g. (you do not need to specify dev)

spin(..., format = 'Rnw')

The output will be LaTeX/PDF instead of HTML in this case.

0
votes

If I understand the question, repeating the plot statement after closing the device has worked without producing a duplicate in the report:

Some random code and plots...

pdf('Figure1.pdf')
plot(important plot)
dev.off()
plot(important plot)

Some random code and plots