Are rCharts and DT compatible in rmarkdown? - r

I am trying to create a document with rmarkdown that includes both plots from the rCharts package and a datatable using the DT library included in htmlwidgets.
For some reason I cannot display both of them together.
---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE}
library(DT)
library(rCharts)
df<-data.frame(Name=c("a","Z","h","k","j"),Value=(sample(10^7,5)))
datatable(df, filter = 'top', options = list(
pageLength = 10,iDisplaylength=10, autoWidth = TRUE
))
```
```{r, message=FALSE, echo=FALSE, results='asis'}
df<-data.frame(label=c("One","Two","Three"),valuea=c(1,2,3),
othera=c(10,11,12),stringsAsFactors = FALSE)
p1 <- nPlot(valuea~ label, data = df, type = 'pieChart')
#Different options I tried
p1$print('inline', include_assets = TRUE, cdn = FALSE)
#p1$show('inline', include_assets = TRUE, cdn = FALSE)
#p1$print('inline', include_assets = TRUE)
#p1$show('inline', include_assets = TRUE)
#These provide an error
#p1$print('inline', include_assets = TRUE, cdn = TRUE)
#p1$show('inline', include_assets = TRUE, cdn = TRUE)
```
The commented lines are the things I have tried.
Note I: if p1$print('inline', include_assets = TRUE, cdn = FALSE) is commented the datatable is displayed properly.
Note II: I am aware of p1$save() function combined with an iframe, however, I would like to use the chart inline.

The jQuery library is included at the top of the page and when you include_assets in the print, the it is included again which causes issues.
To fix this, you can try setting include_assets to false and adding the required libraries except jQuery "by hand".
p1 <- nPlot(valuea~ label, data = df, type = 'pieChart')
cat("<link rel='stylesheet' href=.../R/3.1/library/rCharts/libraries/nvd3/css/nv.d3.css>
<link rel='stylesheet' href=.../R/3.1/library/rCharts/libraries/nvd3/css/rNVD3.css>
<script type='text/javascript' src=.../R/3.1/library/rCharts/libraries/nvd3/js/d3.v3.min.js></script>
<script type='text/javascript' src=.../R/3.1/library/rCharts/libraries/nvd3/js/nv.d3.min-new.js></script>
<script type='text/javascript' src=.../R/3.1/library/rCharts/libraries/nvd3/js/fisheye.js></script> ")
p1$print('inline', include_assets = F, cdn = FALSE)
You can find the required libraries and links by running p1$print('inline', include_assets = T, cdn = FALSE) in R, they will be the first lines of output. The src paths are absolute so I replaced some of it by ... in the code above.

Related

dfSummary() graphs are not printed in the HTML file

When using dfSummary() from the "summarytools" package in Rmarkdown -file, I get Graph -part of the summary printed as plain ASCII despite the st_options(plain.ascii = FALSE). The correct graphs are printed in the /tmp -folder, but are not displayed in the html-file.
{r Summary, results='asis', echo=FALSE}
st_options(bootstrap.css = FALSE,
plain.ascii = FALSE,
style = "rmarkdown",
dfSummary.silent = TRUE)
st_css()
dfSummary(df_data, tmp.img.dir = "/tmp", valid.col = FALSE, graph.magnif = 0.75)
Summary from the code above gets printed like this:
How can I get the proper graphs (which are in the tmp-folder nice and shiny) included in the HTML file?
How can I get the proper graphs (which are in the tmp-folder nice and shiny) included in the html file?
According to the Dominic's vignette - "Recommendations for Using summarytools With Rmarkdown":
For dfSummary(), grid is recommended.
So, you may try following, using print() function:
```{r Summary, results = "asis", cache = FALSE}
base::print(summarytools::dfSummary(df_data,
valid.col = FALSE, # drop Valid column if redundant
style = "grid", # set style to “grid”
plain.ascii = FALSE,
graph.magnif = 0.75, # zoom factor (max = 1) for bar plots and histograms
tmp.img.dir = "./tmp"),
dfSummary.silent = TRUE, # Suppresses messages about temporary files
bootstrap.css = FALSE)
```
Or, if you prefer to declare st_options() first:
```{r Summary2, results = 'asis', echo = FALSE}
st_options(bootstrap.css = FALSE,
dfSummary.silent = TRUE)
st_css()
dfSummary(df_data,
valid.col = FALSE,
style = "grid",
plain.ascii = FALSE,
graph.magnif = 0.75,
tmp.img.dir = "./tmp")
```
Let us know if this is helpful.
Just add style="grid":
dfSummary(df_data, style = "grid", tmp.img.dir = "/tmp",
valid.col = FALSE, graph.magnif = 0.75)
The documentation is not clear enough on this point, it'll be fixed in the next version.

Retrieve and execute example code from an R package function as a codeblock in R-markdown

I want to extract the example code from an R package and run it in an rmarkdown file automatically.
I am able to extract the code using the function utils::example as follows.
example("geom_histogram", package = "ggplot2", ask = F,
prompt.prefix = "", give.lines = TRUE)[-(1:5)]
I have tried to use chunk options results="asis" as follows, but the result is given as code output rather than code chunk.
```{r,echo = FALSE, results="asis"}
cat("```{r}")
library(ggplot2)
cat(paste(example("geom_histogram", package = "ggplot2", ask = F,
prompt.prefix = "", give.lines = TRUE)[-(1:5)], collapse = "\n"))
cat("```")
```
I would like to have the code as a code block and the output from the same as in http://ggplot2.tidyverse.org/reference/geom_histogram.html. How to achieve this?
Updated answer:
You can create a function to extract code and use it as a code argument in chunk option.
# Function saved in functions.R file
getCode <- function(myFunction, myPackage) {
example(myFunction, myPackage, ask = FALSE, character.only = TRUE,
prompt.prefix = "", give.lines = TRUE)[-(1:5)]
}
Your Rmd (myFile.Rmd) should look like this:
```{r, meta, include = FALSE}
myPackage <- "ggplot2"
myFunction <- "geom_histogram"
source("functions.R")
```
```{r, intro, echo = FALSE, results = "asis"}
cat("#", myPackage, "\n")
cat("##", myFunction, "\n")
library(myPackage, character.only = TRUE)
```
```{r, runCode, code = getCode(myFunction, myPackage)}
```
Knit Rmd with: knitr::knit2html("myFile.Rmd") for a result like this:
Previous answer:
Write extracted code to a dummy file (foo.R) and use it as a code argument in chunk option.
Example file (myFile.Rmd):
First chunk: loads tested library
Second chunk: extracts example and saves it to a file
Third chunk: runs extracted code
```{r, meta, include = FALSE}
library(ggplot2)
```
```{r, getCode, include = FALSE}
code <- example("geom_histogram", package = "ggplot2", ask = FALSE,
prompt.prefix = "", give.lines = TRUE)[-(1:5)]
write.table(code, "foo.R", quote = FALSE, row.names = FALSE, col.names = FALSE)
```
```{r, runCode, code = readLines("foo.R")}
```
knit file with knitr::knit2html("myFile.Rmd") for a result like this:
We can also remove hard-coded variables to have a more flexible output:
```{r, meta, include = FALSE}
myPackage <- "ggplot2"
myFunction <- "geom_histogram"
library(myPackage, character.only = TRUE)
```
```{r, getCode, include = FALSE}
code <- example(myFunction, myPackage, ask = FALSE, character.only = TRUE,
prompt.prefix = "", give.lines = TRUE)[-(1:5)]
write.table(code, "foo.R", quote = FALSE, row.names = FALSE, col.names = FALSE)
```
```{r, intro, echo = FALSE, results = "asis"}
cat("#", myPackage, "\n")
cat("##", myFunction, "\n")
```
```{r, runCode, code = readLines("foo.R")}
```

After upgrading: rCharts not working in rmarkdown

after I upgraded to rCharts version 0.4.5 I am not able to see a plot in my rmarkdown file anymore. I have produced a minimum example rmd where I cannot see the plots anymore (if I open the output in my browser). I have absolutely no clue which package is responsible for this. Note that it works fine if I use the $save mode and just import the created html file as in example number 2.
Do you have any idea?
I created a minimum example from a highcharts demo. This thread also helped me.
```{r echo = F, message = F, cache = F}
# Set options for plots.
library(knitr)
opts_chunk$set(results = 'asis', comment = NA, message = F, tidy = F, echo=FALSE, cache=FALSE)
```
```{r, echo=FALSE}
library(rCharts)
a <- hPlot(Pulse ~ Height, data = MASS::survey, type = "bubble", title = "Zoom demo", subtitle = "bubble chart", size = "Age", group = "Exer")
a$chart(zoomType = "x")
a$exporting(enabled = T)
a$show('iframesrc', cdn = TRUE)
```
```{r, echo=FALSE}
library(rCharts)
a <- hPlot(Pulse ~ Height, data = MASS::survey, type = "bubble", title = "Zoom demo", subtitle = "bubble chart 2", size = "Age", group = "Exer")
a$chart(zoomType = "x")
a$exporting(enabled = T)
a$save('plot2.html', standalone = TRUE)
```
<iframe src="plot2.html" height="450" width="850" frameBorder="0"></iframe>
The answer is a new "feature", that transforms links of e.g. sources starting with http://www. as //www. to make it also work with https://. On webservers, this is interpreted correctly but if you open a local html file, //www. will not be recognized. The issue is reported on the github page.

Display two rCharts NVD3 figures next to each other in rmarkdown

I want to display two charts with the rCharts package, one next to the other, more or less like the two pies are displayed in this link:
http://nvd3.org/examples/pie.html
I have a partial solution using <iframe>, but the solution has three problems:
It is too case specific
Including controls becomes a complicated task
It does not look too nice
Minimum working example:
---
title: "Example"
output: html_document
---
```{r rcht, message=FALSE, echo=FALSE, results='asis'}
library(rCharts)
df<-data.frame(label=c("One","Two","Three"),valuea=c(1,2,3),othera=c(10,11,12),
valueb=c(4,5,6),otherb=c(10,11,12),stringsAsFactors = FALSE)
p1 <- nPlot(valuea~ label, data = df, type = 'pieChart',height = 225, width = 300)
p2<- nPlot(valueb~ label, data = df, type = 'pieChart',height = 225, width = 300)
p1$show('inline', include_assets = TRUE, cdn = F)
p2$show('inline', include_assets = TRUE, cdn = F)
```
```{r message=FALSE, echo=FALSE}
p1$save("pie1.html", standalone = TRUE)
p2$save("pie2.html", standalone = TRUE)
```
<div align="center">
<font size="10" color="black" face="sans-serif">Both Pies</font><br>
<p>
<iframe src="pie1.html" height="400" width="400"></iframe>
<iframe src="pie2.html" height="400" width="400"></iframe>
</p>
<div>
I know pie charts should not be used and that I could use a multi-bar chart. However, I want to use this type of layout with other kinds of charts in the rCharts package.
Additionally, I would like to include controls in the charts whilst they are shown next to each other. Including the following code before the $save() function adds the controls:
```{r message=FALSE, echo=FALSE}
p1$addControls('y','valuea',values=c('valuea','othera'))
p2$addControls('y','valueb',values=c('valueb','otherb'))
```
This issue is less relevant to me, but if someone has a solution (preferably with only one control for both charts), it would be great.
I understand all this might be too much to handle from R. Any help/advice is appreciated.
Not elegant, but functional (I did not try it with controls):
---
title: "Example"
output: html_document
---
```{r rcht, message=FALSE, echo=FALSE, results='asis'}
library(rCharts)
library(htmltools)
df <- data.frame(label=c("One","Two","Three"),valuea=c(1,2,3),othera=c(10,11,12),
valueb=c(4,5,6),otherb=c(10,11,12),stringsAsFactors = FALSE)
p1 <- nPlot(valuea~ label, data = df, type = 'pieChart',height = 225, width = 300)
p2 <- nPlot(valueb~ label, data = df, type = 'pieChart',height = 225, width = 300)
```
```{r echo=FALSE, results="asis"}
cat("<table width='100%'><tr style='width:100%'><td width='50%'>")
```
```{r echo=FALSE, results="asis"}
p1$show('inline', include_assets = TRUE, cdn = FALSE)
```
```{r echo=FALSE, results="asis"}
cat("</td><td>")
```
```{r echo=FALSE, results="asis"}
p2$show('inline', include_assets = TRUE, cdn = FALSE)
```
```{r echo=FALSE, results="asis"}
cat("</td></tr></table>")
```
Hi I am having the same problem with controls it looks that in the viewer of R-studio everything works fine but not when I compile with Rmarkdown it doesn't show the plot at all.
```{r results = 'asis', comment = NA}
require(rCharts)
require(datasets)
p2 <- nPlot(mpg ~ cyl, group = 'wt',
data = mtcars, type = 'scatterChart')
p2$xAxis(axisLabel = 'Log2')
p2$yAxis(axisLabel = 'Log2')
p2$chart(tooltipContent = "#! function(key, x, y, e){
return '<b>Name:</b> ' + e.point.GeneID
} !#")
p2$chart(color = c('red', 'green'))
p2$addControls("x", value = 'mpg', values = names(mtcars))
p2$addControls("y", value = 'cyl', values = names(mtcars))
cat('<style>.nvd3{height: 400px;}</style>')
p2$print('chart2', include_assets = TRUE)
```
The code above is the addControls are removed actually works also in the rmarkdown.
Also, if you try to run the code above in Rstudio console (just from p2<-nPlot to cat command) and then calling p2 I can actually see the controls.

embed rChart in Markdown

I am trying to embed a NVD3 chart in a Markdown document. I am on a Ubuntu64 system with RStudio 0.98.932, R 3.1.0, rCharts 0.4.2, the browser is Chrome.
The instructions/code from this link:
```{r}
library(rCharts)
library(knitr)
opts_chunk$set(comment = NA, results = "asis", comment = NA, tidy = F)
hair_eye_male = subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = 'Eye',
data = hair_eye_male, type = 'multiBarChart'
)
n1$set(width = 600)
# n1$show('iframesrc', cdn = TRUE) # option 1
# n1$show('inline', include_assets = TRUE, cdn = TRUE) # option 2
```
Neither of the options [n1$show] work, I just get code in a browser. Is there another way of including NVD3 documents in Markdown?
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.
Source:Knitr HTML in R Markdown
This code is working for me. I am using ubuntu64 and same config you mentioned.
```{r, echo=FALSE,results='asis',comment=NA}
library(rCharts)
hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = "Eye", data = hair_eye_male, type = "multiBarChart")
n1$show('iframesrc',cdn=TRUE)
```
Note : you must write results='asis' and comment = NA in chunk options and not use opts_chunk$set as you have in your code block and what you pasted to copy.com.

Resources