为什么我不能使用 fig.cap - Latex through Sweave + Knitr

Why can't i use fig.cap - Latex through Sweave + Knitr

我是 Latex 的新手,我正在尝试创建带有图形标题的图形。

现在,当我尝试在块标题(第二个块)中添加 fig.cap 时,出现错误

Latex error: Not in outer par mode

我的代码

<<echo = FALSE>>= 
source("analysis.R")

repoData <- readRDS("data/repoData.rds")

  a4width<- 8.3
  a4height<- 11.7
@
\begin{figure}[h]
<<echo = FALSE, fig.width= a4width, fig.height=0.35*a4height>>=
G2(repoData)
@
\end{figure}


## ---- G2 ----
G2 <- function(df) {
  # For inflation graph  
  plot <- ggplot(df, aes(x = Month, y = Percent)) +

    geom_line(colour = "firebrick") +
    xlab("") +
    ylab("Repo rate") +
    theme_classic() + 
    theme(axis.title.y = element_text(vjust = 1))

  return(plot)

}

为什么会发生这种情况,如何解决?

您应该从 Sweave 文件中省略 \begin{figure}(未显示在您的 MWE 中)和 \end{figure};当您指定 fig.cap 时,它们由 knitr 自动生成(并且在您的 MWE 的情况下是冗余的,会导致错误)。

如果您需要指定其他 LaTeX 图形选项,请参阅 knitr chunk options documentation 的 "Plot" 部分:特别是,如果您想使用位置 "h",请使用 fig.pos="h" 在你的块选项中,如

所示

fig.pos: (''; character) a character string for the figure position arrangement to be used in \begin{figure}[fig.pos]