【发布时间】: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 的软件包可能是原因,并且非常感谢您解决这个问题。
【问题讨论】: