Using ggvis in Rnw with knitr

五迷三道 提交于 2019-12-01 07:31:23

问题


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.


回答1:


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:

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...



来源:https://stackoverflow.com/questions/27193287/using-ggvis-in-rnw-with-knitr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!