【发布时间】:2016-12-16 02:35:17
【问题描述】:
我正在尝试在使用 knitr/rmarkdown 生成的 PDF 中交叉引用图形和表格。在 SO 和 tex.stackexchange 上有一些问题(例如here 和 here),建议内联执行此操作的方法是添加 \ref{fig:my_fig},其中 my_fig 是块标签。但是,当我在我的 rmarkdown 文档中尝试这样做时,我得到了 ?? 数字应该在哪里。我想了解如何让交叉引用正常工作。
下面是一个可重现的示例。有两个文件:rmarkdown 文件加上一个 header.tex 文件,我已经包括在内,以防它影响答案(尽管无论我是否包括 header.tex 文件,我都有同样的问题)。
在rmarkdown 文件中有三个交叉引用示例。示例 1 是交叉引用失败的图形(显示?? 而不是图形编号)。还有第二次注释掉的尝试(基于this SO answer),我尝试在块之前和之后使用latex 标记设置图形环境、标签和标题,但这会导致pandoc 错误时我试着编织文件。错误是:
! Missing $ inserted. <inserted text> $ l.108 , '%B %e, %Y')`"
output:
pdf_document:
fig_caption: yes
includes:
in_header: header.tex
keep_tex: yes
fontsize: 11pt
geometry: margin=1in
graphics: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message=FALSE, warning=FALSE, fig.height=2, fig.width=4)
```
# Example 1. Figure
This is a report. Take a look at Figure \ref{fig:fig1}.
```{r fig1, echo=FALSE, fig.cap="This is a caption"}
plot(mtcars$wt, mtcars$mpg)
```
<!-- Now, let's take a look at this other plot in Figure \ref{fig:fig2}. -->
<!-- \begin{figure} -->
<!-- ```{r fig2, echo=FALSE} -->
<!-- plot(mtcars$cyl, mtcars$mpg) -->
<!-- ``` -->
<!-- \caption{This is another caption} -->
<!-- \label{fig:fig2} -->
<!-- \end{figure} -->
# Example 2: `xtable`
Some more text. See Table \ref{tab:tab1} below.
```{r echo=FALSE, results="asis"}
library(xtable)
print.xtable(
xtable(mtcars[1:3,1:4], label="tab:tab1", caption="An xtable table"),
comment=FALSE)
```
# Example 3: `kable`
Some more text. See Table \ref{tab:tab2} below.
```{r tab2, echo=FALSE}
library(knitr)
kable(mtcars[1:3,1:4], caption="A `kable` table")
```
header.tex文件
% Caption on top
% https://tex.stackexchange.com/a/14862/4762
\usepackage{floatrow}
\floatsetup[figure]{capposition=top}
\floatsetup[table]{capposition=top}
PDF 输出
【问题讨论】:
-
这里似乎已经讨论过这个问题:I can't generate \label{fig:mwe-plot} with knitr。硬编码
{r fig1, echo=FALSE, fig.cap="\\label{fig:fig1}This is a caption"}似乎有效。
标签: r latex knitr r-markdown cross-reference