pick either png or pdf in knitr when both are available - r

I like to generate both pdf and png image files when I create a (latex) document using knitr. This can be done using dev = c("pdf", "png").
However, I don't seem to be able to choose (on a per-figure) basis which of the two is picked in my latex figure environment. Currently the only way in which I can get, say, a png input file for Fig. 1 and a pdf input file for Fig. 2 is to generate only the required format (by using dev = "png", fig.ext = "png").
Is there a way in which I can still generate both, but at the latex level can select which one is shown? It could be solved easily by allowing an extension in the \includegraphics command, I suppose.
Any input appreciated...
Ron
Minimal example:
\documentclass[a4paper,12pt]{article}
%\VignetteEngine{knitr::knitr}
\DeclareGraphicsExtensions{.pdf,.png}
\begin{document}
%\maketitle
<<knitrInitialization,echo=FALSE>>=
require("knitr", quietly=TRUE)
opts_chunk$set(comment=NA,background='transparent',size='small',fig.width=6,fig.height=6,out.width='\\textwidth',dev=c('pdf','png'))
#
%% this one generates two figures, and the pdf version is shown
%% because of the order in DeclareGraphicsExtensions
\begin{figure}[tb]
\centering
<<testPDF,echo=FALSE>>=
plot(1:10)
#
\caption{PDF figure}
\label{fig:pdf}
\end{figure}
%% if I want to show a png (e.g., because the pdf is too large) I can
%% only do that by not generating a pdf in the first place
\begin{figure}[tb]
\centering
<<testPNG,echo=FALSE,dev='png',fig.ext='png'>>=
plot(1:10)
#
\caption{PNG figure}
\label{fig:png}
\end{figure}
\end{document}

You can simply put
\DeclareGraphicsExtensions{.png,.pdf}
in your document when you want PNG to have precedence, and then
\DeclareGraphicsExtensions{.pdf,.png}
later if you want to go back to the PDF preference. This works in the body of a LaTeX document, not just in the header.

Related

knitr: automate producing multiple versions of PDF for beamer slides

For lectures, I am using knitr to produce LaTeX beamer slides as a PDF. For a given lecture, I want to produce also (a) 1-up handout (using the handout option, and (b) the same handout formatted 4-up.
I find I have to run knitr 3 times to do this as shown below. Is there a way to simplify this work flow?
A lecture stub:
\documentclass[10pt,table]{beamer}
\input{inputs/beamer-setup}
\input{inputs/defs}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
...
\end{document}
And I run knitr as
knit2pdf("Lecture1.Rnw")
To get the 1-up handout (which suppresses the separate pages when you use transitions), I edit the first line to:
\documentclass[10pt,table,handout]{beamer}
and run
knit2pdf("Lecture1.Rnw" output="Lecture1-1up.tex")
Finally, to get the 2 x 2 version, I use the LaTeX pgfpages package,
\documentclass[10pt,table,handout]{beamer}
\input{inputs/beamer-setup}
\input{inputs/defs}
\usepackage{pgfpages}
\pgfpagesuselayout{4 on 1}[letterpaper,landscape]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
And run:
knit2pdf("Lecture1.Rnw" output="Lecture1-4up.tex")
(I found that with beamer, I could not simply print the PDF 4-up using Adobe Acrobat -- it generated a corrupt PDF file. I was forced to use pgfpages)
Then, of course I have to revert my .Rnw file to the original if I need re-do the slides. Very tedious. There must be a better way.

R Chunk option fig.pos not taking effect when generating PDF.

I want to apply the fig.pos= 'h' chunk option like so:
```{r echo=FALSE , fig.pos='h'}
ggplot()
```
so that when I knit to pdf latex positions my plots (the float) at the precise location in the LaTeX code. It is my understanding that this should make my latex code look like:
\begin{figure}[h]
\centering
\includegraphics{files/figure-latex/unnamed-chunk-3-1.pdf}
\end{figure}
but instead when I open the generated Tex document I see:
\begin{figure}[htbp]
\centering
\includegraphics{files/figure-latex/unnamed-chunk-3-1.pdf}
\end{figure}
I am ending up with my plots in random postions in the PDF document instead of where they are located in the latex code, sometimes taking up an entire page for one plot. I have tried fig.pos='h', fig.pos='H',fig.pos='h',fig.pos='h!'and fig.pos='H! based on the table on this page.
I am attempting this based on this link where it states under plot chunk options: fig.pos: (''; character) a character string for the figure position arrangement to be used in \begin{figure}[fig.pos]
What am I missing or how else can I ensure my plots are displayed where the text is located within the Rmd file or latex code?

Why does text 'pdf 2' display when using includegraphics in Sweave

If a pdf document is created using the following Sweave (R/LaTeX) code, then in the top left of the figure there will be text pdf 2; note this is not embedded in the png but is actually text you can highlight.
In the .Rnw:
\begin{figure}[htb]
\centering
<<fig=FALSE,echo=FALSE>>=
png("test0.png",width=4,height=4,units='in',res=1200)
plot(1)
dev.off()
#
\includegraphics{test0.png}
\caption{Demonstration}
\end{figure}
Then in R:
Sweave("report.Rnw") ; texi2pdf("report.tex")
How do I fix this?
I am using a very recent version of R on Ubuntu.
With the following file
\documentclass{article}
\begin{document}
\begin{figure}[htb]
\centering
<<fig=FALSE,echo=FALSE>>=
png("test0.png",width=4,height=4,units='in',res=1200)
plot(1)
dev.off()
#
\includegraphics{test0.png}
\caption{Demonstration}
\end{figure}
there is a null device 1 message that appears before the plot
It is the output of the R commands that generate the plot.
You can suppress it by adding results=hide.
<<fig=FALSE,echo=FALSE,results=hide>>=
Your message is slightly different because dev.off() returns the name of the current device:
there was none in my case (it was a fresh session),
and a previously opened (but not closed) PDF file in your case.

Can I place all sweave figures at the end of the document?

I have a LaTeX manuscript that inputs from a single Sweave file. The file creates plots and places them in the document using <fig=TRUE>.
Is there a way that I can tell all of the figures to go to the end of the document, where the rest of the figures are? All of the other figures are placed at the end with the LaTeX option [ht!]
The only solution I have come up with is to use <fig=FALSE>, save the file as a graphics file, and then call the figure from within LaTeX at the end of the document. Is there a way to do this within the R-code part of the Sweave document itself (presumably this would be easier to do).
Another alternative is to use the LaTeX 'endfloat' package. Add the following to your preamble, and it will put all of the figures at the end.
\usepackage[noheads,nomarkers]{endfloat}
You could also do <chunk_name, fig = TRUE, include = F> in the chunk where you create the plot and call it at the end using
<new_chunk, fig = TRUE>
<<chunk_name>>
#
The image created with fig=TRUE will always have the name:
FILENAME-CHUNKNAME.pdf
Where FILENAME is the name of your .Rnw file without extension, So with this you can easilly make the includegraphics call yourself:
% Somewhere in source:
<<CHUNKNAME,fig=TRUE,include=FALSE>>=
plot(1)
#
% Later in source:
\begin{figure}
\centering
\includegraphics{FILENAME-CHUNKNAME}
\caption{Whatever}
\label{fig:whatever}
\end{figure}

Adding a table of contents to PDF with R plots

I'm creating a larger number of plots in R and save them as PDF (using grDevices / pdf). Is there an easy way to add a (meta-data) table of contents to the PDF as it is created?
I don't mean to add a separate page, but a TOC that PDF viewers like Preview.app display in the sidebar to make navigation easier.)
Example of such a TOC:
The only way I know is with LaTeX, but you don't necessarily need Sweave; perhaps you could just generate the LaTeX file directly with your RPython code. If you've got two pictures which are 6x6 (the default size) named tmp-001.pdf and tmp-002.pdf, this is how you'd make a section called Section A with two subsections for the two pictures.
\documentclass{article}
\usepackage[paperwidth=6in, paperheight=6in, margin=0in]{geometry}
\usepackage{hyperref}
\usepackage{graphicx}
\parindent 0pt
\begin{document}
\pdfbookmark[1]{Section A}{anchorname_aa}
\pdfbookmark[2]{plot aa}{anchorname_aa}
\includegraphics{tmp-001.pdf}
\newpage
\pdfbookmark[2]{plot bb}{anchorname_bb}
\includegraphics{tmp-002.pdf}
\end{document}
You could create a first page using the names of your objects or plots as the arguments to text in columns.
plot(1:10,1:10, type="n", main ="Index", axes=FALSE,frame.plot=FALSE,xlab="")
text(1,10, "plot")
text(3,10, "page")
text(5,1:10, rev(1:10+1))
text(2,1:10, rev(letters[1:10]))
I cannot think of a way to generate a navigable TOC, but this option may be more pleasing and easier to integrate with Beamer-type displays. The Hmisc package function latex provides an interface to the Latex longtable package. My Latex-fu is weak but if yours is stronger, you could also divert the dvi code that is created for integration within other applications. I get an intermediate dvi file put in a temporary directory which then opens my dvi viewer and allows saving as pdf:
require(Hmisc)
?latex # you will probably want to review this
latex(Plot_list<-data.frame(Plots=letters[1:10], Pages=2:11))
Not as far as I know. I think you have to use sweave for that.

Resources