使用 knitr 捕获最终图形标题

使用 knitr 捕获最终图形标题

我正在为 PLOSone 杂志写一篇论文。他们要求将图题放在文章中,而不是放在图本身中(图题是单独提交的)。所以我想知道如何knitr在没有图的情况下输出图题。当然,这不太可能,因为图号和图题在LaTeX运行之前不会最终确定。所以这个问题可能最终需要迁移,但也许有人知道必要的步骤。这是一个 MWE:

\documentclass[10pt, letterpaper]{article}
% Bold the 'Figure #' in the caption and separate it from the title/caption with a period
% Captions will be left justified
\usepackage[aboveskip = 1pt, labelfont = bf, labelsep = period, justification = raggedright, singlelinecheck = off]{caption}

\begin{document}

This is my document.  Here is a cool plot: Fig.~\ref{LabelA}.
<<  ChunkA, fig.cap = "\\label{LabelA}\\bf{A Figure.}" , echo = FALSE >>=
plot(1:10, 1:10)
currCap <- knitr::opts_current$get("fig.cap")
@

<<  ChunkB, results = "asis" , echo = FALSE >>=
cat("\n")
cat(currCap)
@

\end{document}

这不是正确的方法,原因有二。首先,LaTeX可以处理这个,但输出cat(currCap)会创建一个重复的标签,这会造成混淆。其次,我想要的最终 PDF 中的文本行是:

图 1. A 图。

但在编译之前,无法得知这是图 1 而不是其他图LaTeX。下面是 tex 文件的一小部分,显示了上述代码的输出,您可以看到重复标签是如何产生的。

This is my document.  Here is a cool plot: Fig.~\ref{LabelA}.
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{figure}
\includegraphics[width=\maxwidth]{figure/ChunkA-1} \caption{\label{LabelA}\bf{A Figure.}}\label{fig:ChunkA}
\end{figure}
\end{knitrout}
\label{LabelA}\bf{A Figure.}

有人知道如何让它工作吗?

答案1

好吧,这是我自己问题的解决方案,以防其他人想要/需要这样做。

\documentclass[10pt, letterpaper]{article}
\usepackage[nomarkers, nolists]{endfloat}
\usepackage[aboveskip=1pt,labelfont=bf,labelsep=period,justification=raggedright,singlelinecheck=off]{caption}
\begin{document}

<< setUp, echo = FALSE >>=
# Function to report figure captions independent of figures, as required by PLOSone.
# Original idea from Yihui Xie but modified considerably.
# https://github.com/yihui/knitr-examples/blob/master/070-caption-num.Rmd
# Function captures figure caption
x <- NULL
ii <- 0 # Current figure number
fn <- function(x) {
    ii <<- ii + 1 # save updated figure counter into global environment
    figString <<- paste('\\textbf{Figure ', ii, '.} ', x, sep = '') # Current caption saved in global environment
    return(x) # Return original fig.cap so it can be processed normally in the LaTeX figure environment
  }
@

This is my document.  Here is a cool plot: Fig.~\ref{LabelA}.
<<  ChunkA, fig.cap =  fn("\\label{LabelA}\\textbf{A Figure.}"), echo = FALSE >>=
plot(1:10, 1:10)
@

<< figStringA, echo = FALSE , results = "asis" >>=
cat(figString)
@

<<  ChunkB, fig.cap = fn("\\label{LabelB}\\textbf{Another Figure.} Some details about the figure.") , echo = FALSE >>=
plot(1:10, 1:10)
@

<< figStringB, echo = FALSE , results = "asis" >>=
cat(figString)
@

The second figure is Fig.~\ref{LabelB}.  That's all folks!
\end{document}

如果您有includegraphics环境,您将必须包含一些代码来写出图形标题和增量,ii以便图形编号保持正确。

相关内容