首页 > 解决方案 > 如何自动参考 Tufte 讲义中的数字?

问题描述

我正在尝试使用带有 Tufte 讲义输出的 R markdown 编写报告以生成 pdf。我无法使用任何建议的方法在文本中放置图形参考。我希望有人能说明我如何做到这一点。我将不胜感激任何建议。

到目前为止,我已经尝试了两种广泛的方法,这两种方法都在这个 stackoverflow响应中描述。

选项 1:使用\@ref(fig:chunk-label). 这会生成一个在图形标题中具有正确格式的 pdf,但文本中的参考是@ref(fig:fig-margin).. 请参阅脚本下方的图像:

```
---
title: "Markdown example"
date: "`r Sys.Date()`"
output:
  tufte::tufte_handout:
    citation_package: natbib
link-citations: yes
---

```{r setup, include=FALSE}
library(tufte)

```

```{r fig-margin, fig.cap=("MPG vs horsepower, colored by transmission."), fig.height=3.5, fig.margin=TRUE, fig.width=3.5, message=FALSE, cache=FALSE}
library(ggplot2)
mtcars2 <- mtcars
mtcars2$am <- factor(
  mtcars$am, labels = c('automatic', 'manual')
)
ggplot(mtcars2, aes(hp, mpg, color = am)) +
  geom_point() + geom_smooth() +
  theme(legend.position = 'bottom')

```

Insert the figure reference here \@ref(fig:fig-margin).

此处复制的 pdf 中有一张图片,但我没有粘贴它的要点。希望它是可见的
图片

我尝试了多种\@ref(fig:fig-margin)格式的变体,例如删除反斜杠,但无济于事。

选项 2:使用字幕。在上面链接的答案选项中,建议使用 Captioner 作为解决方案,并提供了一些代码。

我实现了这个选项,这次得到了正确的内联引用,但是图 1:图中的部分标题被复制了(即它显示为图 1:图 1:MPG 与马力等)。
这是使用 Captioner 方法的 pdf 中的图像
图片

```
---
title: "Captioner example"
date: "`r Sys.Date()`"
output:
  tufte::tufte_handout:
    citation_package: natbib
link-citations: yes
---

```{r setup, include=FALSE}
library(tufte)
library(captioner)
# invalidate cache when the tufte version changes
knitr::opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)

table_captions <- captioner::captioner()
figure_captions <- captioner::captioner(prefix="Figure.")
fig.cap <- captioner::captioner()

t.ref <- function(label){
  stringr::str_extract(table_captions(label), "[^:]*")
}

f.ref <- function(label){
  stringr::str_extract(figure_captions(label), "[^:]*")
}



```


```{r fig-margin, fig.cap=figure_captions("fig_one", "MPG vs horsepower, colored by transmission."), fig.height=3.5, fig.margin=TRUE, fig.width=3.5, message=FALSE, cache=FALSE}
library(ggplot2)
mtcars2 <- mtcars
mtcars2$am <- factor(
  mtcars$am, labels = c('automatic', 'manual')
)
ggplot(mtcars2, aes(hp, mpg, color = am)) +
  geom_point() + geom_smooth() +
  theme(legend.position = 'bottom')

```

Insert experiment ref here `r f.ref("fig_one")`.

如果可能的话,我的偏好是只使用基本的降价方法,但如果唯一的方法是使用 Captioner,如果有人可以建议摆脱重复,那会很好(我确实尝试对定义的函数进行一些调整在设置块中,但没有一个起作用。

任何建议将不胜感激。B计划当然只是手动完成。

提前致谢。

标签: rr-markdownknitrtufte

解决方案


我在使用 tufte 讲义 (PDF) 时遇到了同样的问题,所以我尝试在没有 @-symbol 的情况下使用\ref大括号,如您在上面链接的SO 线程{ }中的 rmarkdown 示例 #1 中所建议的那样。似乎正在工作。

\ref{fig:my_fig}

推荐阅读