简体   繁体   中英

In knitr, how to set figure width with \textwidth from Latex

I have tried the following to set figure width with knitr and LaTeX:

\documentclass{paper}
\begin{document}
<<fig.width=\textwidth>>
x = runif(1000)
plot(x)
@
\end{document}

However, I get the following error:

<to be read again> 
                >
l.54 <<fig.width=\textwidth>
                        >

What am I doing wrong?

The fig.width option should be numeric for setting the size of the graphic itself. For controlling how the figure is displayed by LaTeX use the out.width and out.height options. These options need to be strings, and you'll need to escape backslashes.

The chunk

<<plot1, fig.width = 5, fig.height = 5, out.width = "0.48\\textwidth">>=
@

will generate a five inch by five inch graphic that will take up 48% of the textwidth in the final document. That is, the file plot1-1.pdf is a five inch by five inch graphic, and the LaTeX code

\includegraphics[width=0.48\textwidth]{figure/plot1-1}

will be placed in the resulting .tex file.

The value of fig.width needs to be something that R can use when setting up the graphics device. It has no idea what \\textwidth will turn out to be, so that won't work. You need to fix a value, typically taken to be a size in inches (but it may be pixels for some devices).

\\textwidth can be used by LaTeX when it typesets your figure, resizing your figure to the requested size. To make this the default use

\setkeys{Gin}{width=\textwidth}

outside of the R code chunks. (This assumes you are using the graphicx package in LaTeX; I forget whether knitr does this automatically.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM