[Tex/LaTex] Is it possible to use pgfplots in Rmarkdown rendered as HTML

htmlpdfpgfplotstikz-pgf

tikzcode renders properly when an Rmarkdown file is rendered in PDF format (which makes sense). In order to make it work in an HTML file, it is required to put the code in an R chunk with the additional option engine = "tikz" for it to work.

I am trying to generate a plot using the pgfplots package. Just like tikz, it generates plots when the .Rmd file is rendered in PDF format, but there does not seem to be any engine option to make it work in HTML format as engine = "tikz" produces an error.

Is there a way to produce pgfplots visualizations in an Rmarkdown file knit as an HTML file?

My minimal reproducible example:

---
title: "Hello World"
author: "Me"
date: "February 17, 2015"
output: html_document
header-includes:
- \usepackage{tikz}
- \usepackage{pgfplots}
---

## TikZ picture
- Here is a TikZ picutre

\begin{tikzpicture}
\draw (0,0) circle (2cm);
\end{tikzpicture}

- Here is another TikZ picutre

\begin{tikzpicture}
\begin{axis}[xmax=9,ymax=9, samples=50]
  \addplot[blue, ultra thick] (x,x*x);
  \addplot[red,  ultra thick] (x*x,x);
\end{axis}
\end{tikzpicture}

Best Answer

You can use tex4ht to convert the TeX file converted from RMarkdown by Knitr and Pandoc. It supports TikZ and most of LaTeX packages.

If you want to convert TikZ code to SVG, it is best to use special driver, which needs to be manually installed unfortunately. To request the driver, add one line to your .rmd file:

---
title: "Hello World"
author: "Me"
date: "February 17, 2015"
output: html_document
header-includes:
- \ifdefined\HCode\def\pgfsysdriver{pgfsys-dvisvgm4ht.def}\fi
- \usepackage{tikz}
- \usepackage{pgfplots}
---

## TikZ picture
- Here is a TikZ picutre

\begin{tikzpicture}
\draw (0,0) circle (2cm);
\end{tikzpicture}

- Here is another TikZ picutre

\begin{tikzpicture}
\begin{axis}[xmax=9,ymax=9, samples=50]
  \addplot[blue, ultra thick] (x,x*x);
  \addplot[red,  ultra thick] (x*x,x);
\end{axis}
\end{tikzpicture}

The file then can be manually converted:

make4ht -f html5+preprocess_input sample.rmd "svg"

make4ht is a compilation script for tex4ht. The -f html5+preprocess_input option executes make4ht extension that can process the RMD source.

This is the resulting HTML document:

enter image description here