I'd like to add a TikZ figure to a bookdown
document in order to include some fancy graphics.
My primary output format is LaTeX which means that I could essentially just include the TikZ graphics verbatim in the Rmarkdown file and it would render fine. However, two problems are haunting me:
- I'd like for the TikZ graphics to be part of a figure environment (for the numbering, caption etc).
- I'd like to be able to render the same code to both PDF (LaTeX) and Gitbook (HTML).
Right now I have the following chunk which nicely produces the relevant graph as a figure when I render to pdf.
```{r, echo=FALSE, engine='tikz', out.width='90%', fig.ext='pdf', fig.cap='Some caption.'}
egin{tikzpicture}[scale=.7]
draw [fill=gray!30,very thick] (0,-1) rectangle (5,1);
draw [very thick] (5, 0) -- (13,0);
ode [below] at (2,-1) {large Hello};
ode [below, align=center] at (0,-1) {large Two\ lines};
end{tikzpicture}
```
However, there are two problems with the code:
- I do not get any output when rendering to gitbook (using
knitr
andbookdown
). I do get the figure caption, however, and if I render tohtml_document
then it works too and I can see the graph. - For PDF the text is rendered using the computer modern font. I'd really like to change this, and the main font in the LaTeX document has already been set to something else. However, because the code is rendered locally by the TikZ engine and then inserted, it is not part of the full LaTeX document. Can I add some LaTeX options, packages etc. that are included by the TikZ engine before the code is rendered?
If there are other ways to include the TikZ code as part of a figure environment then I'd be happy to know.
Update: I guess the second point could be fixed by setting engine.opts = list(template = "latex/tikz2pdf.tex")
where the necessary setup for LaTeX is included in the tikz2pdf.tex
file. That file is read using LaTeX but I'd like to use xelatex
to parse the file since I'm using the fontspec
LaTex package. Can that be changed anyway?