22
votes

I've been been using knitr for a couple of days now, it's great! :)

At the moment I'm struggling to align two plots next to each other in the output file (a PDF). From my understanding this should be achieved by setting out.width='.4\\linewidth' or something similar in the chunk-options.

The resulting plots are quite small, 2 would quite easily fit next to each other, but somehow, the get all placed beneath each other.

I am also having trouble to align latex-tables (xtable-output with results='asis'-option) to the left of the document. It would be great to write next to it.

1
Can you provide a simple minimal example .Rnw file that illustrates it not working?joran
using par(mfrow = c(1, 2)) in the code chunk doesn't do it?Kay

1 Answers

18
votes

Since you haven't provided one, I will do so for you:

\documentclass{article}
\begin{document}

Side by side images:

\begin{figure}[htpb]
<<myChunk, fig.width=3, fig.height=2.5, out.width='.49\\linewidth', fig.show='hold'>>=
par(mar=c(4,4,.1,.1),cex.lab=.95,cex.axis=.9,mgp=c(2,.7,0),tcl=-.3)
plot(cars)
boxplot(cars$dist,xlab='dist')
@
\end{figure}

Ta da!

\end{document}

which results in something that looks roughly like this for me when I run knitr:

enter image description here

Note the fiddling with the par settings to make sure everything looks nice. You will have to tinker.

This minimal reproducible example was derived from the very detailed examples on the knitr website.

Edit

To answer your second question, even though it's more of a pure LaTeX question, here is a minimal example:

\documentclass{article}
\usepackage{wrapfig,lipsum}
%------------------------------------------
\begin{document}
This is where the table goes with text wrapping around it. You may 
embed tabular environment inside wraptable environment and customize as you like.
%------------------------------------------
\begin{wraptable}{l}{5.5cm}
\caption{A wrapped table going nicely inside the text.}\label{wrap-tab:1}
<<mychunk,results = asis,echo = FALSE>>=
library(xtable)
print(xtable(head(cars)),floating = FALSE)
@
\end{wraptable} 
%------------------------------------------
\lipsum[2] 
\par
Table~\ref{wrap-tab:1} is a wrapped table.
%------------------------------------------
\end{document}

Once again, I simply adapted code I found in this question at the amazingly helpful tex.stackexchange.com site.