Cross-reference figure in a separate Rmarkdown (PDF) file

自作多情 提交于 2019-12-11 17:26:00

问题


I am working on a project with two separate .Rmd files that are part of the same project. One file contains text and equations mainly and the other file contains figures/plots. Is it possible to cross-reference the figures from the second file into the first .Rmd file?

File_1.Rmd

The following formula has revolutionized the car manufacturing industry. It predicts the mileage per gallon of a car based on its weight.

$$
mpg = f(wt)
$$

The formula is illustrated in Figure \@ref(fig:File_2.Rmd:plot).

File_2.Rmd

```{r plot}
ggplot(mtcars, aes(wt, mpg)) +
geom_point()
```

The output for both files is bookdown::pdf_document2.


回答1:


Yes, this is possible.

For this to work you must use a chunk label and set a figure caption using the chunk option fig.cap (for example ```{r foo, fig.cap = "some title"}). Doing so will add a caption and a label to the figure environment in the LaTeX document that is used to generate the PDF output. The label of this figure environment will be the chunk label.

It is necessary to use the prefix fig in your reference. Note that there is no need to include the name of the .Rmd file containing the figure you are refering to in the label: \@ref(fig:foo) is sufficient.

Using your example, the following should work:

File_1.Rmd

The following formula has revolutionized the car manufacturing industry. It predicts the mileage per gallon of a car based on its weight.

$$
mpg = f(wt)
$$

The formula is illustrated in Figure \@ref(fig:plot).

File_2.Rmd

```{r plot, fig.cap = "some title"}
ggplot(mtcars, aes(wt, mpg)) +
geom_point()
```

See the documentation of the bookdown package for a more detailed explanation.



来源:https://stackoverflow.com/questions/51345405/cross-reference-figure-in-a-separate-rmarkdown-pdf-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!