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

Rmarkdown: cross-reference image included with markdown syntax

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

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

我正在使用 bookdown::pdf_document2

这可能吗?

可以使用语法 ![caption](path/to/image){#fig:anchor_name}.

将标签附加到 markdown 中包含的图像

也就是说,还有两个选择

  1. 使用 LaTeX 的 \includegraphics 命令。
  2. 使用 knitr 的 include_graphics 函数。

LaTeX 解决方案类似于:

\begin{figure}
   \includegraphics{path/to/picture.png}
   \caption{Caption with spaces}
   \label{fig:example}
\end{figure}

knitr 解决方案看起来像

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

使用这两种解决方案,您可以 cross-reference 生成带有 \ref{fig:example} 的图像。

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

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

id可以随意选择,但要以fig:开头。


如果您希望将所有内容都保留在纯 Markdown 中,但不想手动添加标识符,您可以使用 pandoc Lua filter:

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

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

output:
  bookdown::pdf_document2:
    pandoc_args: ['--lua-filter', 'auto-image-ids.lua']

您可以添加带有 R 的图像:

{r schematic, echo=FALSE, fig.cap="Diseño de circuito esquemático", fig.align="center"}
knitr::include_graphics("schematic.png")

然后引用图像: \ref{fig:schematic}

注意:我尝试了其他方式来引用图像,例如 \@ref(fig:schematic) 但这对我不起作用