简体   繁体   中英

Figure caption for LaTeX diagram in R markdown using knitr

I'm writing a .rmd file to be converted to a .pdf using knitr. In my markdown file, I have a series of classic R plots being generated in chunks and hence both numbered and captioned by knitr.

Now, I'd like to add and caption a simple causal diagram generated in LaTeX before showing my R plots. How do I go about getting my LaTeX diagram numbered as a figure in the same sequence of my other R plots? And how about adding a caption to my LaTeX figure?

A simple example of my rmarkdown document to illustrate:

---
title: "Figure captions"
output: 
    pdf_document:
        fig_caption: yes
        number_sections: yes
header-includes:
    - \usepackage{tikz}
    - \usetikzlibrary{arrows, shapes, positioning, calc}
---

# A simple LaTeX diagram with no caption

This LaTeX diagram should register as 'Figure 1':

\tikzset{line/.style = {draw, -latex},
        cloud/.style = {draw, ellipse, node distance=3cm,
                        minimum height=2em}
}
\begin{tikzpicture}[node distance = 6cm, auto]
    \node [cloud] (init) {Z1};
    \node [cloud, below left = 2 of init] (X1) {X1}; 
    \node [cloud, below right = 2 of init] (Y1) {Y1};
    \node [cloud, below = of init] (Z2) {Z2};
    \path [line] (X1) -- (Y1);
    \path [line] (init) -- ($(X1)!0.5!(Y1)$);
    \path [line] (Z2) -- ($(X1)!0.5!(Y1)$);
\end{tikzpicture}


# A simple R plot with a caption

Here is a generic R plot that should be 'Figure 2', but is generated as 'Figure 1':

```{r figure2, echo=FALSE, fig.cap="This should be called Figure 2"}
library(ggplot2)
qplot(mpg, wt, data = mtcars)
```

In other words, I'm looking for a way to have knitr recognize my LaTeX diagram as a plot on par with the plots generated in my code chunks, so I can simply count it as another figure in the sequence. How can I do this?

As it looks like you're including LaTeX code in your markdown file already, can you just wrap your tikz code in a standard figure environment? I believe the numbering is done by LaTeX, not by knitr, so knitr shouldn't need to know that this is a figure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM