12

I would like to plot 2 figures side-by-side using knitr. I know I could use par(mfrow=c(1,2)), but I've done a lot of work making the figures just right as they are. I've seen this (Two column layout with text and knitr chunk), and it's not working for me.

Ideally, I'd like to do something like this (which fails):

\documentclass[a4paper,11pt]{article}
\begin{document}
\begin{frame}
   \begin{columns}
      \begin{column}{.5\linewidth}
          <<echo=FALSE,eval=TRUE,out.width='4cm',out.height='4cm'>>=
             plot(1:10)
          @
      \end{column}
      \begin{column}{.5\linewidth}
          <<echo=FALSE,eval=TRUE,out.width='4cm',out.height='4cm'>>=
             plot(1:10)
          @
      \end{column}
    \end{columns}
\end{frame}
\end{document}

Using Sweave, I could do the following:

<<plot1, echo=FALSE,eval=TRUE>>=
    plot(1:10)
@

\begin{figure}[htbp]
  \begin{minipage}[h]{0.5\linewidth}
    \begin{center}

        <<label=figplotFlowSingle,echo=FALSE>>=
            <<plot1>>
        @
    \subcaption{Default plot1}
    \label{fig:plot1}
    \end{center}
  \end{minipage}
  \begin{minipage}[h]{0.5\linewidth}
    \begin{center}

        <<plot2, echo=FALSE,eval=TRUE>>=
             plot(1:10)
        @

        <<label=plot22,echo=FALSE>>=
            <<plot2>>
         @
    \subcaption{Default plot2}
    \label{fig:plot2}
    \end{center}
  \end{minipage}
  \caption{}
  \label{fig:plot1and2}
\end{figure}
0
25

If all you want is two figures side by side, you can put the code in one chunk and set fig.show='hold' with an appropriate width, e.g.

\documentclass{article}

\begin{document}  

<<test, out.width='4cm', out.height='4cm', fig.show='hold'>>=
plot(1:10)
plot(rnorm(100))
@

\end{document}

If you want to center the figures, just add an option fig.align='center'. If you want to add captions, you can use fig.cap. See the documentation for all possible options here.

2
  • Thanks so much for the quick answer and awesome package! – ldecicco Jun 6 '13 at 13:38
  • 1
    Does this also work for a table and a plot? – Cos Dec 20 '18 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.