Unable to compile Plotly charts from R sweave to pdf - r

I'm unable to convert charts created by plotly in R sweave to Pdf. But other charts can be created. Is there any other additional code needs to be added for plotly charts?
Below is an example
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<echo = FALSE>>=
C1<-c("A","B","C")
C2<-c(10,20,30)
Df<-data.frame(C1,C2)
#
\begin {figure}
<<echo = FALSE, fig = TRUE>>=
suppressWarnings (library (plotly))
plot_ly(Df, x = ~C1, y = ~C2, type = "bar")%>% layout(title = "ABC")
#
\caption {PlotlyChart}
\end {figure}
Normal Chart
\begin {figure}
<<echo = FALSE, fig = TRUE>>=
barplot(Df[ ,2], names.arg = Df[ ,1])
#
\caption {Normal_Chart}
\end {figure}
\end{document}
When I try a normal box plot in R, it works. Only when I add Plotly chart, I get an error message as
Running pdflatex on ABC.tex...failed
Error running /Library/TeX/texbin/pdflatex (exit code 1)
I'm new to R sweave and Latex, so any help is appreciated. Thanks!

Plotly produces javascript code that draws the plot. This code is to be executed within a web browser. Plotly is usable when generating an HTML document only. No PDF, no Latex.
BUT you can use package webshot with phantomjs to save the plotly as an image, then include the image as a figure.
First install webshot:
install.packages("webshot")
webshot::install_phantomjs()
Then modify you Sweave file like this:
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<echo = FALSE>>=
C1<-c("A","B","C")
C2<-c(10,20,30)
Df<-data.frame(C1,C2)
#
<<echo = FALSE, fig = FALSE>>=
suppressWarnings (library (webshot))
suppressWarnings (library (plotly))
py <- plot_ly(Df, x = ~C1, y = ~C2, type = "bar")%>% layout(title = "ABC")
export(py, file = "myplot.png")
#
\begin {figure}
\includegraphics{myplot.png}
\end {figure}
\end{document}

Related

R sweave generating only .eps

I'm using R sweave (*.Rnw) and want to generate only plotname.eps.
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
\SweaveOpts{eps=TRUE}
<<plotname, fig=TRUE, echo=F, prefix=F>>=
ggplot(data=data, aes(x = day, y = outside_act))
#
\end{document}
When I compile this code, three plots are generated: plotname.eps and plotname.pdf.
How can I suppress R sweave from generating plotname.pdf? (I only need plotname.eps and I don't want R sweave to run this chunk an additional times.)
You can use \SweaveOpts{eps=TRUE, pdf=FALSE}. For full details on the options available, run vignette("Sweave") in the R console.
However, if all you want is the EPS file and not the document, you can just generate it directly, using
setEPS()
postscript("filename.eps")
ggplot(data=data, aes(x = day, y = outside_act))
dev.off()
in an R script.

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

2 Knitr/R Markdown/Rstudio issues: Highcharts and Morris.js

I'm presently trying to replicate a few different types of rCharts using my own data. The first is a HighCharts graph with the following code:
````{r}
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8a.csv")`
require(slidify)
require(rCharts)
require(rHighcharts)
```
```{r}
x<-data.frame(blah,stringsAsFactors=TRUE)
colnames(x)<-substr(colnames(x),2,5)
a<-rHighcharts:::Chart$new()
a$chart(type="column")
a$title(text="Percent of Students on Grade Level on G8 FCAT for Reading (1), Math (2), Writing (3), and Science (4)")
a$xAxis(categories=rownames(x))
a$yAxis(title=list(text="Percent Proficient"))
a$data(x)
```
When this is run as a chunk, the graph is produced nicely, but when I use Knit HTML in markdown, it sticks at the preview stage for a while and when I terminate it, it gives a "status 15" message, which I'm unclear what that means and how it should be resolved.
A second graph I'm trying is a Morris.js graph in Markdown with knitr. I took my R code and put into R Markdown which looks like:
```{r}
library(slidify)
library(knitr)
library(rCharts)
library(RColorBrewer)
library(reshape2)
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8.csv")
blah
```
```{r}
m2<-mPlot(x="year",y=colnames(blah)[-1],data=blah, type="Bar")
m2$set(barColors=brewer.pal(4,"Spectral"))
m2$set(xlab="Year")
m2$set(postUnits="%")
m2$set(hideHover="auto")
m2
```
When I run the chunks, it produces a nice graph the way I expected with an html file of (file:///C:/Users/ypetscher/AppData/Local/Temp/RtmpW4q3ka/filed284f137718.html); however, when I click on Knit HTML, I obtain a file which includes the code, but doesn't produce the graph. Additionally, when Google Chrome comes up I receive an error of :
"No webpage was found for the web address:
file:///C:/Users/YPETSC~1/AppData/Local/Temp/Rtmpk1Pfbp/filee0c383670e0.html
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be
found."
Any help would be greatly appreciated in diagnosing these issues. Thank you much!
NOTE: This is the same solution I posted in the knitr google group.
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Hope this helps.

allowframebreaks in beamer shading box disappear using knitr

I have the following code
\documentclass{beamer}
\begin{document}
<<setup, include=FALSE>>=
opts_chunk$set(out.lines = 4)
opts_chunk$set(size = 'footnotesize')
options(width=60)
knit_hooks$set(document = function(x) {
gsub('\\\\(begin|end)\\{kframe\\}', '', x)
})
#
After I do this, the R source code and output which is supposing to be displayed in a shaded box now disappear. Any idea on how to get the shaded box back?

Dynamic references to figures in a R comment within Sweave document

I would like to find a way to use the LaTeX \ref{} markup to comment in the R code within a Sweave .Rnw file. Here are two examples, one in print
http://cm.bell-labs.com/cm/ms/departments/sia/project/nlme/UGuide.pdf
and one to use to work with:
The .Rnw file
% File: example.Rnw
\documentclass{article}
\usepackage{fullpage}
\usepackage{graphics}
\usepackage{Sweave}
\usepackage[margin = 10pt, font=small, labelfont={bf}]{caption}
\begin{document}
Here is an example file to show what I want to do. I would like to figure out how to use the \LaTeX\ reference command to reference a figure being generated by R code. Note in the R code, in a comment there is a reference to the figure, but of course the output file shows a verbatim copy of the \LaTeX\ markup. Does anyone know how to get something for Figure \ref{fig2}?
<< example plot >>=
library(reshape)
library(ggplot2)
n <- 100
lambda <- 1 / 3
x <- seq(0, qexp(0.999, rate = lambda), length = n)
q1.a <- data.frame(x = x,
f = dexp(x, rate = lambda),
F = pexp(x, rate = lambda))
q1.a <- melt(q1.a, id.vars = 'x')
g <- ggplot(q1.a) + # Produces \ref{fig1}
aes(x = x, y = value) +
geom_line() +
facet_wrap( ~ variable, scale = "free_y")
ggsave(g, filename = "example1.jpeg")
#
\begin{figure}[h]
\centering
\includegraphics[width = 0.48\textwidth]{./example1}
\caption{Exponential Distribution based plots.}
\label{fig1}
\end{figure}
Here is more of what I would like to see:
<< example plot 2 >>=
ggsave(g + geom_point(), filename = "example2.jpeg") # Produces Figure 2
#
\begin{figure}
\centering
\includegraphics[width = 0.48\textwidth]{./example2}
\caption{Exponential Distribution based plots with points and lines.}
\label{fig2}
\end{figure}
\end{document}
and the pdf is build with the R commands
Sweave(file = 'example.Rnw',
engine = "R",
keep.source = 'TRUE',
echo = 'TRUE',
results = 'verbatim')
tools::texi2dvi(file = "example.tex",
pdf = TRUE,
clean = TRUE)
Any insight on how do this would be great.
Here is one way to solve this issue by redefining the Sinput environment in which source code is wrapped by Sweave. By default, it is a simple verbatim environment which is not processed by latex for tokens. The trick is to redefine it to use the alltt environment which allows some tokens to be parsed inside the alltt environment. Note that this might lead to unwanted side effects that I am not aware of, so use with caution!
Here is a reproducible example that works. If you compile it, you will generate a file where ref{fig1} is replaced by the figure number.
\documentclass{article}
\usepackage{Sweave}
\usepackage{alltt}
\renewenvironment{Sinput}{\begin{alltt}}{\end{alltt}}
\begin{document}
In this document, we will create a plot using `R`, and reference its position in
the source code.
<<produce-plot, results = hide>>=
pdf('example1.pdf')
plot(1:10, 1:10) # Produces Figure \ref{fig1}
dev.off()
#
\begin{figure}
\includegraphics{example1.pdf}
\caption{Figure 1}
\label{fig1}
\end{figure}
\end{document}

Resources