我试图在knitr/rmarkdown生成的PDF中交叉引用图表.关于SO和tex.stackexchange(例如here和here),有一些问题表明,内联操作的方法是添加\ref{fig:my_fig}
,其中my_fig
是块标签.然而,当我在我的rmarkdown
文档中try 这一点时,我得到的数字应该是??
.我想了解如何使交叉引用正常工作.
下面是一个可复制的例子.这里有两个文件:rmarkdown
文件加上header.tex
文件,以防它影响答案(尽管我有同样的问题,不管我是否包括header.tex
文件).
rmarkdown
文件中有三个交叉引用示例.示例1是交叉引用失败的图形(显示??
而不是图形编号).还有第二个注释掉的try (基于this SO answer),我try 在区块前后用latex
个标记设置图形环境、标签和标题,但在我try 编织文档时,这会导致pandoc
个错误.错误是:
! Missing $ inserted. <inserted text> $ l.108 ![](testCrossRef_
例2使用xtable
和交叉引用作品.例3使用kable
,交叉引用失败.
PDF输出的截图包含在这篇文章的底部.
rmarkdown
file
---
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
file
% Caption on top
% https://tex.stackexchange.com/a/14862/4762
\usepackage{floatrow}
\floatsetup[figure]{capposition=top}
\floatsetup[table]{capposition=top}