[Tex/LaTex] Using subcaption package with knitr

knitrsubcaption

How can I use subcaption package in knitr, instead of the obsolete subfig and \subfloat?

Or, maybe, specify additional options with fig.env = 'subfigure'? It needed something like this:

\begin{subfigure}[b]{0.3\textwidth}
  <code>
\end{subfigure}

But using only fig.env produces, missing the {0.3\textwidth}:

\begin{subfigure}[!htb]
  \includegraphics[width=\maxwidth]{}
  \caption[]{}
  \label{}
\end{subfigure}

Best Answer

Looking at the knitr option docs and following it to an example code, it seems that you'd just redefine the \subfloat-command, like this: \newcommand{\subfloat}[2][need a sub-caption]{\subcaptionbox{#1}{#2}}.

Here is an example:

\documentclass{article}
\usepackage{subcaption}
\newcommand{\subfloat}[2][need a sub-caption]{\subcaptionbox{#1}{#2}}

\begin{document}
    <<someChunk,cache=T,echo=F,tidy=F, fig.subcap=c("Subfig1", "Subfig2") , fig.cap="TITLE", out.width='.49\\linewidth'>>=
      x=seq(1:10)
      plot(x,x)
      plot(x,x^2)
    @
\end{document}

Although, it might be some other way to actually use an environment instead of a command to display figures, I didn't find any. Yet.


Also note that fig.env only sets the "parent" environment, like \begin{figure}, so it seems that if you want to use fig.env, you'd have to do it in separate environments, something like this:

\begin{figure}
  <<someChunk,cache=T,echo=F,tidy=F, fig.subcap=c("Subfig1", "Subfig2") , fig.cap="TITLE", out.width='.49\\linewidth', fig.env=c('subfigure')>>=
    x=seq(1:10)
    plot(x,x)
  @
  <<someChunk,cache=T,echo=F,tidy=F, fig.subcap=c("Subfig1", "Subfig2") , fig.cap="TITLE", out.width='.49\\linewidth', fig.env=c('subfigure')>>=
    x=seq(1:10)
    plot(x,x^2)
  @
\end{figure}

The latter example won't work, since subfigure needs an argument, and I'm not really sure how to do that.