Search code examples
latexr-markdowntikz

Use r object in tikz chunk in Rmarkdown


I'm trying to figure out to add R variables in a tikz chunk. Is there any way to achieve this.

Here is an example

---
output: pdf_document
---

```{r, echo = FALSE}
TEXT <- 1
```

```{tikz, echo = FALSE}
\begin{tikzpicture}
\node (x) at (0,0) {$x$};
\node (y) at (3,0) {$y$};
\draw[->] (x) to node [anchor = north] {`r TEXT`} (y);
\end{tikzpicture}
```

I would like the r TEXT to be replaced by whatever is in TEXT.


Solution

  • You don't actually need a tikz chunk, you can just load the package yourself:

    ---
    output: pdf_document
    header-includes:
      - \usepackage{tikz}
    ---
    
    ```{r, echo = FALSE}
    TEXT <- 1
    ```
    
    \begin{tikzpicture}
    \node (x) at (0,0) {$x$};
    \node (y) at (3,0) {$y$};
    \draw[->] (x) to node [anchor = north] {`r TEXT`} (y);
    \end{tikzpicture}
    

    enter image description here