I tried to change some of my scripts from sweave
to knitr
and have found that subfigure failed to render properly when using knitr while they were correct with sweave. I am well aware that knitr offers a way to produce subfigure in knitr header options like in this post, but my question I have several long reports and would like to re-use these code with minimal change. In addition I would like to understand why when using knitr, a simple subfigure example fails.
Example with sweave
In sweave (1) to respect standard knitr output I save the figure in the figure subdirectory, and I create two pdf figures. This is the code for the .Rnw file to be processed using sweave()
.
\documentclass[a4paper]{article}
\usepackage{graphicx}
\usepackage{subcaption}
\usepackage{float}
\graphicspath{{figure/}}
\title{test for sweave}
\date{}
\begin{document}
\maketitle
<<multiplefig, echo= FALSE, results=hide>>=
dir.create("figure",showWarnings = FALSE)
mapply(function(X){
pdf(paste0(getwd(),"/figure/fig-",X,".pdf"),height=6,width=6)
plot(X,main=X)
dev.off()
},c(1:2))
@
\begin{figure}[htbp]
\centering
\begin{subfigure}[b]{0.45\textwidth}
\centering
\includegraphics{fig-1}
\caption{subcaption1}
\end{subfigure}%
~
\begin{subfigure}[b]{0.45\textwidth}
\centering
\includegraphics{fig-2}
\caption{subcaption2}
\end{subfigure}
\caption{Subfigures properly placed side by side in sweave using
the subfigure command.}
\end{figure}
\end{document}
Example with knitr
With knitr, the output is produced straight from the R code chunk, but when using the subfigure command there is a problem.
\documentclass[a4paper]{article}
\usepackage{subcaption}
\usepackage{float}
\graphicspath{{figure/}}
\title{problem when using knitr}
\date{}
\begin{document}
\maketitle
<<init, include=FALSE>>=
library(knitr)
@
<<knitrfig, fig.height=6, fig.with=6, include=FALSE>>=
mapply(function(X)plot(X,main=X),c(1:2))
@
This is where the problem lies
\begin{figure}[htbp]
\centering
\begin{subfigure}[b]{0.45\textwidth}
\centering
\includegraphics{knitrfig-1}
\caption{subcaption1}
\end{subfigure}%
~
\begin{subfigure}[b]{0.45\textwidth}
\centering
\includegraphics{knitrfig-2}
\caption{subcaption2}
\end{subfigure}
\caption{With knitr the figure is not rendered properly}
\end{figure}
\end{document}
This problem is not linked with the size of the image, I can reproduce it by using the figures fig1 and fig2 produced by the first (sweave) code chunk. I think that some of the packages loaded with knitr might be the cause, and would be much gratefull for a solution to this problem.