rlatextikzr-examspgfplots

How to avoid "! LaTeX Error: Environment axis undefined" when using include_tikz with pgfplots?


I have successfully included in an R/exams .Rmd file several graphics made in TikZ. The same does not happen when I try to include a plot under pgfplots using include_tikz(). Whenever \begin {axis} and \end {axis} are included, beware of the error "! LaTeX Error: Environment axis undefined".

In the RStudio console the legend appears: "This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020) (preloaded format = pdflatex) restricted \ write18 enabled.entering extended mode", even having enabled in TexStudio write-18. None of these messages appear when I include other TikZ graphs other than pgfplots.

Any TikZ graph works when run in TexMaker or TexStudio, which indicates that it is not a problem of the absence of LaTeX libraries or packages.

I include a part of my code, adapted from https://www.latex4technics.com/?note=1HCT:

```{r datos1, echo = FALSE, results = "hide"}

library(exams)
typ <- match_exams_device()

image01<-'
         \\begin{tikzpicture}
         \\begin{axis}[legend pos=south east]
         \\addlegendimage{empty legend}
         \\addplot {sqrt(x)}; 
         \\addplot {ln(x)}; 
         \\addlegendentry{\\hspace{-.6cm}\\textbf{A title}}
         \\addlegendentry{$\\sqrt{x}$}
         \\addlegendentry{$\\ln{x}$}
         \\end{axis}
         \\end{tikzpicture}
         '
```

```{r grafica01, echo = FALSE, results = "asis"}
include_tikz(image01, name = "grafiko1", markup = 
"markdown",format = typ,library = c("arrows"),packages = 
"booktabs",width = "7cm",header = "\\usepackage{/home/r- 
exams/Documentos/NuevoRStudio/Rmarkdowns/
Esqueleto/exercises/schoice/ 
LaboratorioTikZ/3dplot}")
```

Solution

  • The answer is right there in your question title. You need to include the pgfplots package:

    include_tikz(image01, packages = "pgfplots", ...)
    

    The other packages, library, and header arguments from the call in your question are not needed.

    The reason is that for include_tikz() you just use the {tikzpicture} code while in the full .tex file that you linked you additionally have:

    \documentclass{standalone}
    \usepackage{pgfplots}
    \begin{document}
    \begin{tikzpicture}
    ...
    \end{tikzpicture}
    \end{document}
    

    Note the \usepackge{pgfplots} in the second line!