Rmarkdown:markdown 语法中包含的交叉引用图像

Sig*_*ide 5 latex cross-reference r-markdown bookdown

我想交叉引用我包含在降价![caption with spaces](path/to/image.png)语法中的图像。

我希望能够将此图像交叉引用为\@ref(fig:caption-with-spaces).

我正在使用bookdown::pdf_document2.

这可能吗?

tar*_*leb 8

R Markdown 在通过 R 生成图形时添加图形 ID,但不适用于纯 Markdown 图像。在这种情况下,您可以自己添加一个ID:

![Caption with spaces](path/to/pictures.png){#fig:caption-with-spaces}
Run Code Online (Sandbox Code Playgroud)

id可以自由选择,但应以.开头fig:


如果您想将所有内容保留在纯 Markdown 中,但不想手动添加标识符,您可以使用pandoc Lua 过滤器

![Caption with spaces](path/to/pictures.png){#fig:caption-with-spaces}
Run Code Online (Sandbox Code Playgroud)

pandoc_args通过向输出设置添加参数来使用:

local stringify = (require 'pandoc.utils').stringify
function Image (img)
  if img.identifier == '' then
    img.identifier = 'fig:' .. stringify(img.caption):gsub('%s', '-'):lower()
    return img
  end
end
Run Code Online (Sandbox Code Playgroud)


Ral*_*lph 6

可以使用语法将标签附加到 Markdown 中包含的图像![caption](path/to/image){#fig:anchor_name}

也就是说,还有两个进一步的选择

  1. 使用 LaTeX 的\includegraphics命令。
  2. 使用 knitr 的include_graphics功能。

LaTeX 解决方案如下所示:

\begin{figure}
   \includegraphics{path/to/picture.png}
   \caption{Caption with spaces}
   \label{fig:example}
\end{figure}
Run Code Online (Sandbox Code Playgroud)

knitr 解决方案看起来像

```{r, fig.cap = "Caption with spaces", label="example"}
knitr::include_graphics("path/to/picture.png")
```
Run Code Online (Sandbox Code Playgroud)

使用这两种解决方案,您都可以使用\ref{fig:example}.