使用子图时knitr中的意外输出

时间:2018-01-14 15:33:49

标签: r latex knitr sweave

我尝试将我的一些脚本从sweave更改为knitr,并且发现当使用knitr时子图未能正确呈现,而它们与sweave一致。我很清楚knitr提供了一种在knitr头选项中生成子图的方法,就像在这个post中一样,但我的问题是我有几个很长的报告,并希望以最小的改变重复使用这些代码。另外我想了解为什么在使用knitr时,一个简单的子图示例失败了。

带有sweave的示例

在sweave(1)中尊重标准knitr输出我将图保存在图子目录中,并创建两个pdf数字。这是使用sweave()处理的.Rnw文件的代码。

\documentclass[a4paper]{article}
\usepackage{graphicx} 
\usepackage{subcaption}
\usepackage{float}
\graphicspath{{figure/}}
\title{test for sweave}
\date{}
\begin{document}
\maketitle

<<multiplefig, echo= FALSE, results=hide>>=
    dir.create("figure",showWarnings = FALSE)
    mapply(function(X){
          pdf(paste0(getwd(),"/figure/fig-",X,".pdf"),height=6,width=6)
          plot(X,main=X)
          dev.off()
        },c(1:2))

@


\begin{figure}[htbp]
 \centering
    \begin{subfigure}[b]{0.45\textwidth}
        \centering
        \includegraphics{fig-1}
        \caption{subcaption1}
    \end{subfigure}%
    ~ 
    \begin{subfigure}[b]{0.45\textwidth}
        \centering
        \includegraphics{fig-2}
        \caption{subcaption2}
    \end{subfigure}
    \caption{Subfigures properly placed side by side in sweave using
    the subfigure command.}
\end{figure}
\end{document}

输出是这样的: sweave correct output

knitr

的例子

使用knitr,输出直接从R代码块产生, 但是在使用子图命令时会出现问题。

\documentclass[a4paper]{article}
\usepackage{subcaption}
\usepackage{float}
\graphicspath{{figure/}}
\title{problem when using knitr}
\date{}
\begin{document}
\maketitle
<<init, include=FALSE>>=
library(knitr) 
@
<<knitrfig, fig.height=6, fig.with=6, include=FALSE>>=
    mapply(function(X)plot(X,main=X),c(1:2))
@



This is where the problem lies
\begin{figure}[htbp]
 \centering
    \begin{subfigure}[b]{0.45\textwidth}
        \centering
        \includegraphics{knitrfig-1}
        \caption{subcaption1}
    \end{subfigure}%
    ~ 
    \begin{subfigure}[b]{0.45\textwidth}
        \centering
        \includegraphics{knitrfig-2}
        \caption{subcaption2}
    \end{subfigure}
    \caption{With knitr the figure is not rendered properly}
\end{figure}
\end{document}

knitr_subfigure_output

这个问题与图像的大小无关,我可以使用第一个(sweave)代码块产生的数字fig1和fig2来重现它。我认为一些装有knitr的软件包可能是原因,并且非常感谢解决这个问题。

1 个答案:

答案 0 :(得分:0)

我想我理解为什么。

首先我意识到如果我将命令\usepackage{Sweave}添加到knitr tex输出中,我就不再有这个数字问题了。 在sweave代码中搜索,我发现它包含以下命令:

\ifthenelse{\boolean{Sweave@gin}}{\setkeys{Gin}{width=0.8\textwidth}}{}%

在这篇SO帖子中,David Calisle解释说使用

 \setkeys{Gin}{width=0.8\textwidth,height=0.8\textheight,keepaspectratio}

将命令应用于以下所有\ includegraphics。

所以我在加载Sweave时对我的数字宽度有限制,但我没有意识到这一点,当我尝试使用knitr时它不再有效。也许这会对遇到同样问题的其他人有用。我只需要将\setkeys{Gin}{width=0.8\textwidth}添加到我的脚本中。