图*环境在twocolumn knitr / Sweave文件中

时间:2012-01-23 23:00:45

标签: r knitr tex sweave

听起来应该是一个常见的问题,但我没有找到明显的伎俩。 考虑下面的knitr Rnw文件,

\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf, fig.align=center}
\begin{figure*}
<<aaa, fig.width=8, fig.height=5, fig.show=hold>>=
plot(1,1)
@
\end{figure*}
\end{document}

我希望这个宽图能够使用{figure*} LaTeX环境跨越两列。是否有钩子?

编辑:将块包装​​在figure*中会得到以下输出。

enter image description here

3 个答案:

答案 0 :(得分:6)

两个事实:

  1. knitr让您可以访问所有内容,因此通常不需要使用LaTeX技巧;
  2. 有一个chunk hook可以用来包装你的块结果;
  3. 一个简单的解决方案是:

    knit_hooks$set(chunk = function(x, options) {
                           sprintf('\\begin{figure*}\n%s\n\\end{figure*}', x)
    })
    

    我将剩余的工作留给您处理options中的更多详细信息(例如,options$fig.keep == 'none'时,您不应将输出包装在figure*中)。您可能希望了解knitr中如何定义La {the default chunk hook以更好地了解chunk挂钩的工作原理。

    但是,在这种情况下,我倾向于在文档中自己编写LaTeX代码,而不是自动创建它。获得figure*后,您可能会开始考虑\caption{}\label{}not hard,但我仍希望在LaTeX中看到它们。)

答案 1 :(得分:2)

不确定如何编织,但对于Sweave(和基本乳胶)实际上有一个技巧:让R代码生成pdf文件,然后使用标准\includegraphics将其拉入。

所以这个:

\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf}

<<aaa,fig=FALSE,print=FALSE,echo=FALSE>>=
pdf("mychart.pdf", width=6, height=3)
set.seed(42)
plot(cumsum(rnorm(100)), type='l', main="yet another random walk")
invisible(dev.off())
@

\begin{figure*}
  \includegraphics{mychart.pdf}
\end{figure*}

\end{document}

我得到了下面的文件(然后我从pdf转换为png):

enter image description here

答案 2 :(得分:1)

在制作一个应该跨越IEEE两栏会议论文中两栏的数字时,我也遇到了类似的问题。

设置chunk hook会导致我的设置出现一些奇怪的错误。 即便是这个简单的钩子:knit_hooks$set(chunk = function(x, options) x)

但在调查knitr::opts_chunk$get()之后,我意识到只需设置fig.env="figure*"就可以优雅地解决问题。

以下是我的块在Rnw文件中的样子:

<<fig1, fig.width=18, fig.height=6, fig.env="figure*">>=
@