Search code examples
rlatexrstudioknitrggvis

Using ggvis in Rnw with knitr


I wonder if I can use ggvis in .Rnw with knitr. I tried the following code in RStudio Version 0.98.1091. But it is not working.

\documentclass{book}
\usepackage[T1]{fontenc}
\usepackage{float}
\usepackage{booktabs}
\usepackage{dcolumn}
\usepackage{geometry}
\geometry{verbose,tmargin=2cm,bmargin=2cm,lmargin=2cm,rmargin=2cm}

\begin{document}
\chapter{Test}
\begin{figure}[H]
<< label = Plot1, fig.lp = "Plot1", fig.cap = "Test Plot" >>=
library(ggvis)
p <- mtcars %>% ggvis(x = ~wt, y = ~mpg) %>% layer_points()
print(p)     # Commenting this line will compile the document
@
\end{figure}
\end{document}

It throws the following error:

LaTeX errors:
! Missing $ inserted.
<inserted text> 
                $
l.70 \end{kframe}<!--html_
                          preserve--><div id="plot_id298740869-container" cl...
! Please use \mathaccent for accents in math mode.

Edited

Commenting the line print(p) will compile the document without any error.

Would be sufficient if there is a command like ggsave() to save the ggvis plots.


Solution

  • Yes.

    The export_png function can create a PNG image from a ggvis object.

    It uses the node javascript interpreter, and node needs the vega package installed.

    At the linux command line, I can do this with:

    sudo npm -g install vega
    

    to install the vega package globally using the node package manager. I don't know how you do this on a Windows or Mac box.

    Once that's done, you can:

    \documentclass{book}
    \usepackage[T1]{fontenc}
    \usepackage{float}
    \usepackage{booktabs}
    \usepackage{dcolumn}
    \usepackage{geometry}
    \geometry{verbose,tmargin=2cm,bmargin=2cm,lmargin=2cm,rmargin=2cm}
    
    \begin{document}
    \chapter{Test}
    \begin{figure}[H]
    << label = Plot1, fig.lp = "Plot1", fig.cap = "Test Plot" >>=
    library(ggvis)
    p <- mtcars %>% ggvis(x = ~wt, y = ~mpg) %>% layer_points()
    export_png(p,"Plot1.png")    
    @
    \includegraphics[width=0.8\textwidth]{Plot1.png}
    \end{figure}
    \end{document}
    

    do: knit2pdf("gg.Rnw")

    and get:

    enter image description here

    Note you'll have to add captions and labels manually. Perhaps Yihui can be persuaded to integrate this better into knitr, or there may be a way using some of the knitr hooks. Anyway, concept proved...