【问题标题】:Unexpected output in knitr when using subfigures使用子图时 knitr 中的意外输出
【发布时间】:2018-06-23 09:16:10
【问题描述】:

我尝试将我的一些脚本从 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}

输出是这样的:

knitr 示例

使用 knitr,输出直接从 R 代码块生成, 但是在使用 subfigure 命令的时候就出现了问题。

\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}

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

【问题讨论】:

    标签: r latex knitr sweave


    【解决方案1】:

    我想我明白为什么了。

    首先我意识到,如果我将命令 \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} 添加到我的脚本中即可。

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      相关资源
      最近更新 更多