【问题标题】:In knitr, how to set figure width with \textwidth from Latex在 knitr 中,如何使用 Latex 中的 \textwidth 设置图形宽度
【发布时间】:2017-10-30 01:30:20
【问题描述】:
我尝试了以下方法来使用 knitr 和 LaTeX 设置图形宽度:
\documentclass{paper}
\begin{document}
<<fig.width=\textwidth>>
x = runif(1000)
plot(x)
@
\end{document}
但是,我收到以下错误:
<to be read again>
>
l.54 <<fig.width=\textwidth>
>
我做错了什么?
【问题讨论】:
标签:
latex
width
knitr
figure
【解决方案1】:
fig.width 选项应该是数字,用于设置图形本身的大小。要控制 LaTeX 显示图形的方式,请使用 out.width 和 out.height 选项。这些选项必须是字符串,并且您需要转义反斜杠。
块
<<plot1, fig.width = 5, fig.height = 5, out.width = "0.48\\textwidth">>=
@
将生成一个 5 英寸 x 5 英寸的图形,它将占据最终文档中文本宽度的 48%。即文件plot1-1.pdf是一个五英寸乘五英寸的图形,LaTeX代码
\includegraphics[width=0.48\textwidth]{figure/plot1-1}
将放置在生成的 .tex 文件中。
【解决方案2】:
fig.width 的值必须是 R 在设置图形设备时可以使用的值。它不知道 \textwidth 会变成什么,所以这是行不通的。您需要固定一个值,通常以英寸为单位(但对于某些设备可能是像素)。
\textwidth 可以在 LaTeX 排版您的图形时使用,将您的图形调整为请求的大小。将此设为默认使用
\setkeys{Gin}{width=\textwidth}
在 R 代码块之外。 (假设您在 LaTeX 中使用 graphicx 包;我忘记了 knitr 是否会自动执行此操作。)