Render rCharts in slides from Slidify - r

Recently I have been experimenting with slidify and rCharts. Tutorials for generating simple charts while using slidify are explanatory, but I was unable to find any such tutorial regarding rCharts.
For example, I know that the following generates an interactive plot
data(mtcars)
r1<- rPlot(mpg ~ wt | am + vs, data=mtcars, type="point")
data(iris)
hair_eye = as.data.frame(HairEyeColor)
rPlot(Freq ~ Hair | Eye,color = 'Eye', data = hair_eye, type = 'bar')
However, I have no idea how to incorporate the resulting plot into my slides using slidify.
EDIT - After the helpful comment
I tried the following, having seen it on Ramnath's git:
---
title : Practice
subtitle : makes perfect
author : Noob
job :
framework : io2012 # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js # {highlight.js, prettify, highlight}
hitheme : tomorrow #
widgets : [nvd3] # {mathjax, quiz, bootstrap}
mode : selfcontained # {standalone, draft}
---
```{r setup, message = F, echo = F}
require(rCharts)
options(RCHART_WIDTH = 800, RCHART_HEIGHT = 500)
knitr::opts_chunk$set(comment = NA, results = 'asis', tidy = F, message = F)
```
## NVD3 Scatterplot
```{r echo = F}
data(mtcars)
n1 <- nPlot(mpg ~ wt, group = 'gear', data = mtcars, type = 'scatterChart')
n1$print('chart1')
```
But ended up with this error:
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
cannot open file 'libraries/widgets/nvd3/nvd3.html': No such file or directory
After which I decided to copy the nvd3 folder from Ramnath's widgets directly into mine, hoping that this would solve the matter. However, this ended up crazily showing Ramnath's git page as well as my slides in the background!
What to do? I would really appreciate any guidelines/pointers/advice on how to accomplish this task. And, I hope this question aids other novices like myself in using the wonderful rCharts.
Note: I am using the standard editor for R, not R-studio. I feel the former is less cluttered.

All instructions below assume that you have the dev branch of the packages installed (slidify, slidifyLibraries and rCharts). You can accomplish this using install_github.
pkgs <- c("slidify", "slidifyLibraries", "rCharts")
devtools::install_github(pkgs, "ramnathv", ref = "dev")
There are two ways to include an rCharts viz in your slidify document, and the deck below illustrates both ways. If you print a plot in a code chunk, as you would do so in the R console, slidify automatically detects that you are running it in a knitr session and as a result save the resulting html to an iframe and embed it in the deck. Alternately, you can specify the chart inline, in which case you have to use n1$show("inline") and also include ext_widgets: {rCharts: libraries/nvd3} in your YAML front matter.
The iframe method is the default and the recommended method to avoid conflicts between various javascript files and css. The inline method does work well for several rCharts libraries, but make sure to check before you use.
---
title : rCharts Integration
ext_widgets : {rCharts: libraries/nvd3}
mode: selfcontained
---
## NVD3 Plot Inline
```{r nvd3plot, results = 'asis', comment = NA, message = F, echo = F}
require(rCharts)
n1 <- nPlot(mpg ~ wt, data = mtcars, type = 'scatterChart')
n1$show('inline')
```
---
## NVD3 Plot Iframe
```{r nvd3plot2, results = 'asis', comment = NA, message = F, echo = F}
require(rCharts)
n1 <- nPlot(mpg ~ wt, data = mtcars, type = 'scatterChart')
n1
```

Related

R Markdown render fails knit with mlogit, object not found, but code chunks work

I have done a basic search around the site (e.g. R Knit Markdown code chunk: "object not found"), but I don't think I have found anything that fixes my problem, or at least explains why my problem occurs.
There are only a few code chunks in my .rmd which come quite verbatim from https://cran.r-project.org/web/packages/mlogit/vignettes/e1mlogit.html
The first is to load data
rm(list = ls())
library(mlogit)
data("Heating", package = "mlogit")
H <- mlogit.data(Heating, shape = "wide", choice = "depvar", varying = c(3:12))
Then I fit the model, but I use ref_level_var instead of any specific string "gr"
ref_level_var <- "gr"
mc <- mlogit(formula = depvar ~ ic + oc, data = H, reflevel = ref_level_var)
The odd part comes when I try
head(predict(mc, newdata = H))
Now because I require my files to be knit to two different formats (solution via Knit one markdown file to two output files), I use the following knit in my header for the .rmd
knit: (function(inputFile, encoding) {
rmarkdown::render(inputFile, encoding = encoding, output_format = c("html_document", "pdf_document"))})
However, this results in the following error
Error in model.frame.mFormula(formula = depvar ~ ic + oc, data = structure(list(: object 'ref_level_var' not found
Obviously, it seems that somehow ref_level_var is not visible to the knitting session, despite there being a ref_level_var <- "gr" line somewhere. Why does this error occur, and how can I fix it?
Note that the error is very odd, because replacing the whole knit line with output: html_document results in no errors.

R, generate pretty plot by dfSummary

I have a problem using summarytools packet. There is tutorial:https://cran.r-project.org/web/packages/summarytools/vignettes/Introduction.html with pretty plots of data:
My problem is that my code generate only TEXT GRAPH. This is chunk of code in my markdown to generate plot:
```{r summary, results='markup'}
library(summarytools)
my_data <- ...
dfSummary(my_data)
```
Unfortunately it generates something like this:
How can I generate this pretty report using summarytools?
Or have you better tools for this? (generate graph, mean, std, etc.)
I found the correct syntax to generate plot:
print(dfSummary(baseline_train), method = 'render')
And the results look like this:
A little update on this:
Always use knitr chunk option results='asis', as someone pointed in an earlier comment.
It is possible to generate summaries including png graphs using print():
print(dfSummary(iris), method = "render")
Starting with version 0.9.0 (available only on GitHub as of Feb. 2019), markdown summaries will also include png graphs provided you specify the following arguments:
plain.ascii = FALSE
style = "grid"
a physical location for temporary png's (tmp.img.dir)
dfSummary(iris, plain.ascii = FALSE, style = "grid", tmp.img.dir = "/tmp")
Additionnal tips
In both cases, you will (in all likelihood) need to adjust the size of the graphs with dfSummary()'s graph.magnif parameter (try values between .75 and .85).
Exclude a column or two to avoid overly wide summaries:
dfSummary(iris, [...], varnumbers = FALSE, valid.col = FALSE)
You need to use results = 'asis' for the code chunk. Here is minimal reproducible example:
---
title: "Untitled"
output: html_document
---
```{r, results='asis'}
library(summarytools)
dfSummary(iris, plain.ascii = FALSE, style = "grid")
```
produces

Embeded Plots Missing when Knitting to PDF

I know this question has been asked in different formats, but when searching I couldn't find a solution or problem similar to mine.
Using Mac with RStudio (Version 1.0.153 ) R (version 3.4.3 (2017-11-30) -- "Kite-Eating Tree")
I am just trying to knit to a PDF (weave using knitr) in R markdown, but when I do, the plots are missing. When I knit to HTML the plots are there. I am using the earlywarnings package which helps create the plots. See example below using R markdown:
```{r, earlywarnings, fig.keep='all'}
library(earlywarnings)
data("foldbif")
x = foldbif
plot.ts(x)
```
That plot shows in the pdf output, but not when I create other plots like these:
```{r, echo=FALSE,results='hide',fig.keep='all', fig=TRUE}
out<-generic_ews(x,winsize=50,detrending="gaussian",
bandwidth=5,logtransform=FALSE,interpolate=FALSE)
```
or this one:
```{r, echo=FALSE, results='hide', fig.keep='all', fig=TRUE, warning=FALSE}
qda = qda_ews(x, param = NULL, winsize = 50, detrending = "gaussian",
bandwidth = NULL, boots = 100,s_level = 0.05, cutoff = 0.05,
detection.threshold = 0.002, grid.size = 50, logtransform = FALSE, interpolate = FALSE)
```
The last function also only displays 2 out of 3 plots, but I'll figure that out another time.
Any help would be appreciated. Please let me know if this was not clear.
I can confirm that the issue is related with the use of dev.new(). I copy-pasted the code of the function, removed it (the one line 136 of the function) and it worked, i.e. I get the figure on my pdf. There may be a way to call a function to avoid the effect of dev.new() that I am not aware of.

R markdown doesn't find object

I am using R markdown to knitter my codes into a word document
I am pretty new to R as well as to R markdown
I have the following code :
{r, eval=TRUE, fig.height=7, fig.width=5, message=FALSE, warning=FALSE}
lifeExpectancy <- rename(lifeExpectancy, Incomegroup= WORLDBANKINCOMEGROUP)
plife <- ggplot(lifeExpectancy, aes(x= LifeExpectancy))
plife1 <- plife + geom_histogram(fill="white", aes(color= Incomegroup))
plife1 <- plife1 +facet_grid(SEX~Incomegroup) + xlab("average life
expectancy")
plife1
this is the warning message it returns :
Quitting from lines 32-38 (Termpaper_Franziska.Rmd)
error in rename_(.data, .dots = lazyeval::lazy_dots(...)) :
Object 'lifeExpectancy' not found
calls : <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval
> rename -> rename_
stopped`
What I already did :
I set the working directory correctly for R markdown as well as for my original script
I used
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir =
"C:/Users/Maxi/Desktop/PrettyPlots2016/Termpaper")
to set the working directory but that didn't help either.
Last but not least I also set
eval=FALSE
but then I didn't get my plot of course, which didn't help me either.
If anyone has a solution for my dilemma I would be very happy to hear it !
Thank you a lot !

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.

Resources