Is it possible to produce subfigures (with associated subcaptions) using knitr? Here is a minimal working example:
\documentclass{article}
\begin{document}
<<echo = FALSE, fig.cap = c("Some numbers.", "Some more numbers."), out.width = "0.5\\textwidth", fig.align = "center">>=
plot(1:10)
plot(30:100)
@
\end{document}
This results in two figures labelled Figure 1 and Figure 2 with captions as defined (respectively). But I want them to be labelled "Figure 1a" and "Figure 1b", as you can do with the subcaption LaTeX package.
I know there is a knitr options "fig.env", but this doesn't solve it (at least not using, for example, "fig.env = 'subfigure'"). There is a similar post here regarding Sweave, but the solution is an inelegant hack: http://texblog.org/2011/12/01/sweave-subfig-controlling-figure-size-and-placement/
knitr
(>= v1.5) supports subfigures. You can use the chunk optionfig.subcap
. Here is a minimal example.Updating the answer from Yihui to reflect the changes in Rmarkdown in the past few years, and also the shift away from Rnw files.
As listed within the knitr chunk options, subfigures require a few additional settings to be set in the chunk header:
fig.subcap
is a list of the captions for subfiguresfig.ncol
: the number of columns of subfiguresout.width
: the output width of the figures. You will normally set this 100% divided by the number of sub columns.Subfigures also require the LaTeX package
subfig
. The line\usepackage{subfig}
must therefore be included within the YAML, or if you are using an external tex template you can add this to that file.Here is a basic template:
Using with ggplot2
If you are plotting subfigures which contains multiple ggplot plots, can messy as they do not line up between the plots. You may want to check out this post here on how to use cowplot to force ggplots to have the same dimensions.
This stackoverflow post will help you make sure that all the plots line up as shown in the image below:
Providing a list to subfigures
Just sharing this as a possible extension of subfigures. Something I like to use them for is feeding them a list of figures. Maybe you have produced a function which you need to run on four different trial groups, or in four separate locations. For example, here is a list of four cities in the UK:
This list can then be used within the
fig.sub
and anlapply
to produce a list of subfigures. If you need to run theThis makes the subfigures quite robust. If I need to run my model in an extra couple of cities, all I need to do is add extra values to the
location
list and the sub figures will be the same length.You can use Latex's subcaption package.