我试图在由knitr/rmarkdown生成的PDF中交叉引用图和表。有一些关于SO和tex.stackexchange(例如这里和这里)的问题建议内联使用
这篇文章底部包含PDF输出的截屏。 文件
\ref{fig:my_fig}
,其中my_fig
是块标签的方式来实现此功能。然而,当我在我的rmarkdown
文档中尝试时,在应显示图形编号的位置上会出现??
。我想找出如何使交叉引用正常工作。
以下是一个可重现的示例。有两个文件:一个rmarkdown
文件和一个header.tex
文件,我包含它只是为了防止影响答案(尽管我无论是否包含header.tex
文件都存在同样的问题)。
在rmarkdown
文件中,有三个交叉引用示例。示例1是一个图形,交叉引用失败(应显示??
而不是图形编号)。还有第二个被注释掉的尝试(基于这个SO答案),在这里我尝试在块之前和之后使用latex
标记设置图形环境、标签和标题,但当我尝试编织文档时,这会导致一个pandoc
错误。该错误是:
! Missing $ inserted.
<inserted text>
$
l.108 ![](testCrossRef_
例子2使用xtable
并且交叉引用起作用。例子3使用kable
并且交叉引用失败。这篇文章底部包含PDF输出的截屏。 文件
---
title: |
| My Title
author: |
| eipi10
| Department of Redundancy Department
date: "`r format(Sys.time(), '%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}
{r fig1, echo=FALSE, fig.cap="\\label{fig:fig1}This is a caption"}
似乎有效。 - Weihuang Wong