用 knitr 垂直堆叠的子图

subfigures stacked vertically with knitr

我正在尝试在 Latex 文档中使用 knitr 将两个子图垂直堆叠而不是并排放置。在 Latex 中,我通常通过在需要彼此堆叠的两个子浮点之间放置一个 '\par' 命令来做到这一点,但我不知道如何将该命令传递给 knitr。

我只能找到一个关于此的主题,Subfigures or Subcaptions with knitr?。 Yihui给出的例子将数字并排放置。该线程中的最终答案实现了我的目标,但使用了相当多的黑客攻击,所以我想知道是否有一种简单的方法可以将此命令直接传递给 knitr?

MWE:

\documentclass[a4paper]{article} 

\usepackage[font=footnotesize]{subfig}

\begin{document} 

<<GeneratePlot>>=
library(ggplot2)
library(tikzDevice)
P1 <- ggplot(data=mpg, aes(x=displ, y=hwy, colour=factor(cyl)))+
    geom_line()
P2 <-  ggplot(data=mpg, aes(x=displ, y=hwy, colour=factor(cyl)))+
    geom_point()
@


<<fig1,eval=TRUE,echo=FALSE,dev='tikz', fig.width=6, fig.height=3, out.width='1\textwidth', fig.cap='Two figures', fig.subcap=c('Top','Bottom'), fig.show='asis', fig.pos='!htpb', fig.align='center', dependson='GeneratePlot'>>= 
P1
P2
@ 

\end{document}

我也试过在与输出相同的块中创建绘图对象,但这会产生相同的结果,在我的原始文档中,绘图对象是作为更大块的一部分生成的,因此它将具有与 MWE 相同的结构。

您可以使用非 CRAN 包 oaReporting

\documentclass[a4paper]{article} 
\usepackage{float}
\usepackage{subcaption}

\begin{document} 

<<setup, include=FALSE>>=
knitr::opts_chunk$set(fig.path="figures/")
library(oaReporting)
@

<<GeneratePlot>>=
library(ggplot2)
P1 <- ggplot(data=mpg, aes(x=displ, y=hwy, colour=factor(cyl)))+
    geom_line()
P2 <-  ggplot(data=mpg, aes(x=displ, y=hwy, colour=factor(cyl)))+
    geom_point()
path1 <- createPlot(P1, file="./figures/P1.pdf")
path2 <- createPlot(P2, file="./figures/P2.pdf")
captions <- c("P1", "P2")
@

<<results="asis", fig.keep="none">>=
insertFigures(paths = c(path1, path2), captions=captions,
              generalCaption = "P1 and P2",
              generalLabel = "fig:P1andP2",
              posMultipleFig = "H",
              nCol = 1, 
              width = 0.7)
@

\end{document}

这是 officially supported in knitr 1.17.19 (current on Github)。要在两个子图之间添加 \par,可以使用块选项 fig.sep = '\par',例如,

\documentclass[a4paper]{article}

\usepackage[font=footnotesize]{subfig}

\begin{document}

<<GeneratePlot>>=
library(ggplot2)
library(tikzDevice)
P1 <- ggplot(data=mpg, aes(x=displ, y=hwy, colour=factor(cyl)))+
    geom_line()
P2 <-  ggplot(data=mpg, aes(x=displ, y=hwy, colour=factor(cyl)))+
    geom_point()
@


<<fig1, echo=FALSE,dev='tikz', fig.width=6, fig.height=3, out.width='1\textwidth', fig.cap='Two figures', fig.subcap=c('Top','Bottom'), fig.show='asis', fig.pos='!htpb', fig.sep='\par'>>=
P1
P2
@

\end{document}

输出: