Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

r - Align plots next to each other with knitr

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

documentclass{article}
egin{document}

Side by side images:

egin{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}
%------------------------------------------
egin{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.
%------------------------------------------
egin{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~
ef{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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...