R Markdown HTML数字数字

Nic*_*ton 13 html r caption figure r-markdown

对于HTML格式的R Markdown脚本,是否有人知道如何对字幕中的数字进行编号?

对于PDF文档,标题将说明如下:

图X:一些标题文本

但是,HTML版本的等效标题将简单地说:

一些标题文字

这使得数字的交叉引用数字完全无用.

这是一个最小的例子:

---
title: "My Title"
author: "Me"
output:
  pdf_document: default
  html_document: default
---

```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```


```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
Run Code Online (Sandbox Code Playgroud)

我尝试过设置toc,fig_caption并且number_sections在每种输出格式中,但这似乎不会改变结果.

Mic*_*per 7

提供的其他答案相对过时,使用bookdown软件包已经非常容易.该软件包提供了许多改进,包括Word,HTML和PDF的内置数字编号.

为了能够使用bookdown,您需要先安装包install.packages("bookdown"),然后使用其中一种输出格式.对于HTML,这是html_document2.举个例子:

---
title: "My Title"
author: "Me"
date:  "1/1/2016"
output: bookdown::html_document2
---


```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```


```{r cars2, fig.cap = "Another amazing plot"}
plot(cars)
```
Run Code Online (Sandbox Code Playgroud)

这些数字将编号Figure 1Figure 2.提供代码块被命名并具有标题,我们可以使用语法交叉引用输出,\@ref(fig:foo)其中foo是块的名称,即\@ref(fig-cars).您可以在此处了解有关此行为的更多信息

进一步阅读


Nic*_*ton 5

因此,除非有人有更好的解决方案,否则这就是我想出的解决方案,这种方法存在一些缺陷(例如,如果图形/表格号取决于节号等),但是对于基本的html文档,它可以工作。

在文档顶部的某个位置运行以下命令:

```{r echo=FALSE}
#Determine the output format of the document
outputFormat   = opts_knit$get("rmarkdown.pandoc.to")

#Figure and Table Caption Numbering, for HTML do it manually
capTabNo = 1; capFigNo = 1;

#Function to add the Table Number
capTab = function(x){
  if(outputFormat == 'html'){
    x = paste0("Table ",capTabNo,". ",x)
    capTabNo <<- capTabNo + 1
  }; x
}

#Function to add the Figure Number
capFig = function(x){
  if(outputFormat == 'html'){
    x = paste0("Figure ",capFigNo,". ",x)
    capFigNo <<- capFigNo + 1
  }; x
}
```
Run Code Online (Sandbox Code Playgroud)

然后,在文档处理过程中,如果要说要绘制图形:

```{r figA,fig.cap=capFig("My Figure Caption")
base = ggplot(data=data.frame(x=0,y=0),aes(x,y)) + geom_point()
base
```
Run Code Online (Sandbox Code Playgroud)

替代capFigcapTab在上面,如果你想要一个表格标题。


sco*_*coa 5

我们可以使用pandoc-crossref,这是一个过滤器,允许交叉引用图形、表格、部分和方程,并适用于所有输出格式。最简单的方法是在每个绘图后添加cat图形标签(以 的形式{#fig:figure_label}),尽管这需要echo=FALSEresults='asis'。然后我们可以像引用引用一样引用图形:默认[@fig:figure_label]生成fig. figure_number

这是一个 MWE:

---
output: 
  html_document:
    toc: true
    number_sections: true
    fig_caption: true
    pandoc_args: ["-F","pandoc-crossref"]
---

```{r}
knitr::opts_chunk$set(echo=FALSE,results='asis')

```


```{r plot1,fig.cap="This is plot one"}
x <- 1:10
y <- rnorm(10)
plot(x,y)
cat("{#fig:plot1}")

```

As we can see in [@fig:plot1]... whereas [@fig:plot2] shows...

```{r plot2, fig.cap="This is plot two"}
plot(y,x)
cat("{#fig:plot2}")

```
Run Code Online (Sandbox Code Playgroud)

产生(删除图形

地块1

图 1:这是绘图一

正如我们在图中看到的。1...而图。2 显示…

地块2

图 2:这是图二

有关更多选项和自定义,请参阅pandoc-crossref 自述文件

要安装 pandoc-crossref,假设您安装了 Haskell:

cabal update
cabal install pandoc-crossref
Run Code Online (Sandbox Code Playgroud)