简体   繁体   English

R Markdown HTML数字数字

[英]R Markdown HTML Number Figures

Does anyone know how to number the figures in the captions, for HTML format R Markdown script? 对于HTML格式的R Markdown脚本,有谁知道如何对字幕中的数字进行编号?

For PDF documents, the caption will say something like: 对于PDF文档,标题将说明如下:

Figure X: Some Caption Text 图X:一些标题文本

However, the equivalent caption for the HTML version will simply say: 但是,HTML版本的等效标题将简单地说:

Some Caption Text 一些标题文字

This makes cross-referencing figures by number completely useless. 这使得数字的交叉引用数字完全无用。

Here is a minimal example: 这是一个最小的例子:

---
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)
```

I have tried setting toc , fig_caption and number_sections within each of the output formats, but this does not seem to change the result. 我尝试在每种输出格式中设置tocfig_captionnumber_sections ,但这似乎不会改变结果。

The other answers provided are relatively out of date, and this has since been made very easy using the bookdown package. 提供的其他答案相对过时,使用bookdown软件包已经非常容易。 This package provides a number of improvements which includes the built-in numbering of figures across Word, HTML and PDF. 该软件包提供了许多改进,包括Word,HTML和PDF的内置数字编号。

To be able to use bookdown , you need to first install the package install.packages("bookdown") and then use one of the output formats . 为了能够使用bookdown ,您需要先安装软件包install.packages("bookdown") ,然后使用其中一种输出格式 For HTML, this is html_document2 . 对于HTML,这是html_document2 Taking your example: 举个例子:

---
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)
```

These Figures will be numbered Figure 1 and Figure 2 . 这些图将编号为Figure 1Figure 2 Providing the code chunk is named and has a caption, we can cross reference the output using the the syntax \\@ref(fig:foo) where foo is the name of the chunk ie \\@ref(fig-cars) . 提供代码块是命名的并且有一个标题,我们可以使用语法\\@ref(fig:foo)交叉引用输出\\@ref(fig:foo)其中foo是块的名称,即\\@ref(fig-cars) You can learn more about this behaviour here 您可以在此处了解有关此行为的更多信息

Further Reading 进一步阅读

So unless someone has a better solution, this is the solution that I came up with, there are some flaws with this approach (for example, if the figure/table number is dependent on the section number etc...), but for the basic html document, it works. 因此,除非有人有更好的解决方案,这是我提出的解决方案,这种方法存在一些缺陷(例如,如果图/表编号依赖于部分编号等...),但是对于基本的HTML文档,它的工作原理。

Somewhere at the top of you document, run this: 在文档顶部的某处,运行以下命令:

```{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
}
```

Then during the course of your document, if say you want to plot a figure: 然后在您的文档过程中,如果您想要绘制图形:

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

Substitute the capFig to capTab in the above, if you want a table caption. 如果你想要一个表格标题,将capTab替换为capFigcapTab

We can make use of pandoc-crossref , a filter that allows a cross-referencing of figures, tables, sections, and equations and works for all output format. 我们可以使用pandoc-crossref ,这是一个允许交叉引用图形,表格,部分和方程的过滤器,适用于所有输出格式。 The easiest way is to cat the figure label (in the form of {#fig:figure_label} ) after each plot, although this requires echo=FALSE and results='asis' . 最简单的方法是cat图标签(在形式{#fig:figure_label}每个图后,尽管这需要echo=FALSEresults='asis' Then we can reference a figure as we would a citation : [@fig:figure_label] produces fig. figure_number 然后我们可以参考一个数字,因为我们会引用: [@fig:figure_label]产生fig. figure_number fig. figure_number by default. fig. figure_number默认情况下。

Here is a MWE: 这是一个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}")

```

which produces (removing the graphics 产生(删除图形

PLOT1 PLOT1

Figure 1: This is plot one 图1:这是第一个图

As we can see in fig. 正如我们在图中看到的那样。 1… whereas fig. 1 ...而无花果。 2 shows… 2显示......

PLOT2 PLOT2

Figure 2: This is plot two 图2:这是第二个图

See the pandoc-crossref readme for more options and customizations. 有关更多选项和自定义,请参阅pandoc-crossref自述文件

To install pandoc-crossref, assuming you have a haskell installation: 要安装pandoc-crossref,假设您有haskell安装:

cabal update
cabal install pandoc-crossref

I solve cross-referencing using a solution similar to that posted by Nicholas above. 我使用类似于上面Nicholas发布的解决方案来解决交叉引用问题。 I use bookdown for some projects but I find that awkward to use for other projects where I just want simple cross-referencing. 我在某些项目中使用了bookdown,但我发现在我只想要简单的交叉引用的其他项目中使用它很尴尬。

I use the following when I am writing a paper with rmarkdown and I want it in standard format for submission to a journal. 当我用rmarkdown写一篇论文时,我使用以下内容,我希望它以标准格式提交给期刊。 I want a figure legend at the end, then tables, then I'll have the tables and figures. 我想要一个图形结尾,然后表格,然后我会有表格和数字。 As I am writing, I only have a rough idea of what order the figures will be referenced in the text. 在我写作时,我只是粗略地了解了文本中引用数字的顺序。 I just want to reference them with a text code like fig:foobar and have the number assigned based appearance in the text. 我只想用像fig:foobar这样的文本代码来引用它们,并在文本中指定基于外观的编号。 When I look at the figure legend list, I'll see what order to put the legends and will move legends around as needed. 当我查看图形图例列表时,我会看到传说的顺序,并根据需要移动图例。

Here's my structure. 这是我的结构。

I have an R package where I have things I need for papers, like various bibliographies and helper R functions. 我有一个R包,我有论文需要的东西,比如各种参考书目和辅助R函数。 In that package, I have the following function which uses some variables defined in the main Rmd environment: .rmdenvir and .rmdctr . 在该包中,我有以下函数,它使用在主Rmd环境中定义的一些变量:.rmdenvir和.rmdctr。

ref <- function(useName) {
require(stringr)
if(!exists(".refctr")) .refctr <- c(`_` = 0)
if(any(names(.refctr)==useName)) return(.refctr[useName])
type=str_split(useName,":")[[1]][1]
nObj <- sum(str_detect(names(.refctr),type))
useNum <- nObj + 1
newrefctr <- c(.refctr, useNum)
names(newrefctr)[length(.refctr) + 1] <- useName
assign(".refctr", newrefctr, envir=.rmdenvir)
return(useNum)
}

It assumes that I name things I want referenced with something like cntname:foo, for example fig:foo. 它假定我用cntname:foo之类的名称命名我想引用的东西,例如fig:foo。 It makes a new counter for each one and I can make up new counters on the fly (while writing) if needed. 它为每个人制作了一个新的计数器,如果需要,我可以动态组成新的计数器(写作时)。

In my main Rmd file, I have some set-up lines: 在我的主Rmd文件中,我有一些设置行:

    ```{r setup_main}
    require(myPackageforPapers)
    # here is where the variables needed by ref() are defined.
    .rmdenvir = environment()
    .refctr <- c(`_` = 0)
    ````

In the text I use the following 在文中我使用以下内容

    You can see what I am trying to show in Figure `r ref("fig:foo")`
    and you can see it also in Tables `r ref("tab:foo")` 
    and A`r ref("tabappA:foobig")`.

to get "You can see what I am trying to show in Figure 1 and you can see it also in Tables 1 and A1." 得到“你可以看到我想在图1中展示的内容,你也可以在表1和A1中看到它。” Although the numbers might not be 1; 虽然数字可能不是1; the number to use will be dynamically determined. 使用的数量将动态确定。 I don't have to use a special function for the first time I reference a figure, table or whatever I am counting. 我第一次引用一个图形,表格或者我在计算的任何东西时都不必使用特殊功能。 ref() figures that out by looking to see if the label exists already. ref()通过查看标签是否已存在来计算出来。 If not it assigns the next number, and returns it. 如果不是,则分配下一个号码,然后返回。 So you don't have to use "label" in one place and "ref" in another. 因此,您不必在一个地方使用“标签”,在另一个地方使用“ref”。

In the course of writing, I might decide that appendix A is getting too big, and that I will split off some of the tables into an appendix B. All I need to do is change the above to 在写作过程中,我可能会认为附录A太大了,我会把一些表分成附录B.我需要做的就是将上面的内容改为

    You can see what I am trying to show in Figure `r ref("fig:foo")`
    and you can see it also in Tables `r ref("tab:foo")` 
    and B`r ref("tabappB:foobig")`.

I just specify a new counter name 'tabappB' and the numbers for that are dynamically determined. 我只是指定一个新的计数器名称'tabappB',并且它的数字是动态确定的。

At the end of my Rmd file, I have a figure list that will look like 在我的Rmd文件的末尾,我有一个看起来像的图表

    # Figure Legends

    Figure `r ref("fig:foo")`. This is the legend for this figure.

    Figure  `r ref("fig:foo2")`. This is the legend for another figure.

Then my tables appear like so 然后我的表就像这样

    ```{r print-tablefoo, echo=FALSE}
    tablefoo=mtcars
    thecap = "Tables appear with a legend while figures do not."
    fullcap = paste("Table ", ref("tab:foo"), ". ", thecap, sep="")
    kable(tablefoo, caption=fullcap)
    ```

and then the figures like so: 然后这些数字如下:

    ```{r fig-foo, echo=FALSE, fig.cap=paste("Figure",ref("fig:foo"))}
    plot(1,1)
    ```

Appendix A is an Rmd file that included as a child. 附录A是一个包含在孩子身份的Rmd文件。 It will have tables like 它会有像这样的表

    ```{r print-tableAfoo, echo=FALSE}
    tablefoo=mtcars
    thecap = "This is a legend."
    fullcap = paste("Table A", ref("tabappA:foobig"), ". ", thecap, sep="")
    kable(tablefoo, caption=fullcap)
    ```

I do have to add the "A" to get Table A1, but I find it easier if R doesn't think too much for me in terms of labelling my counters. 我必须添加“A”来获得表A1,但是如果R在标记我的计数器方面对我没有太多想法,我会发现它更容易。 I just I want it to return the right number. 我只是想让它返回正确的数字。

The cross-referencing works for html, pdf/latex or word. 交叉引用适用于html,pdf / latex或word。 I'd happily stick with latex solutions, but my co-authors use word so I need a solution that works with pandoc and word. 我很乐意坚持使用乳胶解决方案,但我的合着者使用了单词,所以我需要一个与pandoc和word一起使用的解决方案。 Also sometimes I want html or some other output and I need a solution that works for any output that works with rmarkdown. 有时我想要html或其他输出,我需要一个适用于任何与rmarkdown一起使用的输出的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM