I am running the dygraph example provided by the following RSTUDIO help page.
http://rstudio.github.io/dygraphs/gallery-synchronization.html
When I run the following code, I get individual plots for each dygraph separately.
dygraph(ldeaths, main = "All", group = "lung-deaths")
dygraph(mdeaths, main = "Male", group = "lung-deaths")
dygraph(fdeaths, main = "Female", group = "lung-deaths")
I don't get the synchronized plots as shown in the help page.
The "group" variable "lung-deaths" is not part of the xts object.
Please let me know if I am missing something basic here.
Thanks
Pradeep
To plot multiple dygraphs in the same RStudio window you must first create a list of dygraphs objects, and then render the dygraphs list using package htmltools. Yihui Xie from RStudio provided the answer here:
Yihui Xie answer (but without grouping).
I answered similar questions here: my answer, and here: my answer.
Here is working R code that produces grouped (synchronized) dygraphs plots:
# create a list of dygraphs objects
library(dygraphs)
library(htmltools)
dy_graph <- list(
dygraphs::dygraph(ldeaths, main = "All", group = "lung-deaths"),
dygraphs::dygraph(mdeaths, main = "Male", group = "lung-deaths"),
dygraphs::dygraph(fdeaths, main = "Female", group = "lung-deaths")
) # end list
# render the dygraphs objects using htmltools
htmltools::browsable(htmltools::tagList(dy_graph))
The above R code produces the following grouped (synchronized) dygraphs plots:
(I can't add a comment because I do not have enough reputation yet.)
By checking the code behind dygraph's gallery (right-click on a graph and choose "Inspect" in Google Chrome), it looks like each graph is its own html element. Therefore they can be synchronized ONLY if they are together on the same html page. This will not work in Rstudio.
If it is possible to plot several dygraph() graphs at once (as asked by #schlusie in this SO question dygraph in R multiple plots at once but with no answer yet), then synchornization might work in Rstudio.
Maybe people who know about css have other opinions.
I encountered the same problem. I could not reproduce the dygraph example on synchronization provided by the gallery help page in RStudio.
However, for my needs of pure visualization I found a workaround discussed on github:
Specify your dygraph objects in a R-script (e.g myscript.R) according to your needs and assign them to variables (e.g. d1 and d2).
d1 = dygraph(ldeaths, main = "All", group = "lung-deaths")
d2 = dygraph(mdeaths, main = "Male", group = "lung-deaths")
Open a R-markdown document, source() your R-script in a code cell and call the variables.
{r, echo=FALSE}
source("myscript.R")
d1
d2
Finally, render the R-markdown document to a html file (Kint to html). By setting echo=FALSE you suppress the alphanumeric output and end up with a html document with synchronized dygraph plots.
Related
Motivation: I want to write an interface that uses questions from the R package exams in learnr questions/quizzes. In R/exams each question is either an R/Markdown (Rmd) or R/LaTeX (Rnw) file with a certain structure specifying question, solution, and further meta-information. The questions can contain R code to make them dynamic, e.g., sampling numbers or certain text building blocks etc. Hence, the workflow is that first the questions are run through knitr::knit or utils::Sweave and then embedded in a suitable output format.
Problem: When I rmarkdown::run("learnr+rexams.Rmd") a learnr tutorial that dynamically produces a question or quiz from an Rmd exercise I get the error:
Error in if (grepl(not_valid_char_regex, label)) { :
argument is of length zero
The code for a simple reproducible example learnr+rexams.Rmd is included below.
The reason for the error appears to be that learnr runs a function verify_tutorial_chunk_label() that tries to assure the the learnr R chunk labels are well formatted. However, confusion is caused by the chunks that are run by the R/exams package, unnecessarily leading to the error above.
Workarounds: I can disable the verify_tutorial_chunk_label() in the learnr namespace and then everything works well. Or I can use Rnw instead of Rmd exercises and then learnr does not conflict with Sweave(). Also, when I run my code outside of a learnr tutorial it works fine.
Question: Can I do anything less invasive to make exams cooperate with learnr? For example, setting some appropriate knitr options or something like that?
Example: This is the source for the minimal learnr tutorial learnr+rexams.Rmd that replicates the problem. Note that everything is very much simplified and only works for certain R/exams exercises, here using the function exercise template that ships with R/exams.
---
title: "learnr & R/exams"
output: learnr::tutorial
runtime: shiny_prerendered
---
```{r exams2learnr, include = FALSE}
exams2learnr <- function(file) {
x <- exams::xexams(file)[[1]][[1]]
x <- list(text = x$question, type = "learnr_text",
learnr::answer(x$metainfo$solution, correct = TRUE))
do.call(learnr::question, x)
}
## assignInNamespace("verify_tutorial_chunk_label", function() return(), ns = "learnr")
```
```{r rfunctions, echo = FALSE, message = FALSE}
exams2learnr("function.Rmd")
```
Running this tutorial (as noted above) replicates the error. To avoid it I can either uncomment the assignInNamespace() call or alternatively replace "function.Rmd" by "function.Rnw".
The problem is that by the time learnr::question() is called, knitr is no longer able to find the chunk label for the chunk where exams2learnr() was called. You can get around this by setting the current chunk label before calling do.call(learnr_question, x):
exams2learnr <- function(file, label = knitr::opts_current$get("label")) {
force(label)
x <- exams::xexams(file)[[1]][[1]]
x <- list(
text = x$question,
type = "learnr_text",
learnr::answer(x$metainfo$solution, correct = TRUE)
)
knitr::opts_current$set(label = label)
do.call(learnr::question, x)
}
This also lets you set the label dynamically if you want, which becomes the ID of the question in learnr.
I’ve been using the dygraphs R package to produce some wonderful timeseries plots, but am having great difficulty reproducing the examples located here:
http://rstudio.github.io/dygraphs/gallery-custom-plotters.html
I’m particularly interested in creating a stacked bar chart:
My data is an xts/zoo object and plots nicely using the standard dygraph function:
However, I am unsure where the dyStackedBarGroup function comes from. It appears these functions must be created, and point to the specific plotters in .js files.
I can see for the first example, how dyBarChart is created, but there is no stackedbarchar.js/stackedbargroup.js in my local dygraph installation (however I can see the file in https://github.com/rstudio/dygraphs/tree/master/inst/plotters).
I’ve attempted to source all the functions and .js files from the github page which do not appear to be made available when loading the dygraphs package locally, but I remain unsuccessful.
Am I doing something completely wrong?
set stackedGraph argument in dyOptions to TRUE. dyOptions(stackedGraph = TRUE).
The javascript file for the barchart can be found at "examples/plotters/barchart.js" of the dygraphs package directory.
Data:
lungDeaths <- cbind(mdeaths, ldeaths)
Code:
# create dygraph plotter
library('dygraphs')
dyBarChart <- function(dygraph) {
dyPlotter(dygraph = dygraph,
name = "BarChart",
path = system.file("examples/plotters/barchart.js", package = "dygraphs"))
}
dygraph(lungDeaths) %>% # create dygraph of lungDeaths
dyBarChart() %>% # create bar chart with the passed dygraph
dyOptions(stackedGraph = TRUE) # make it as stacked bar chart
Summary: my ultimate goal is to use rCharts, and specifically Highcharts, as part of a ReporteRs PowerPoint report automation workflow. One of the charts I would like to use is rendered as html in the Viewer pane in Rstudio, and addPlot(function() print(myChart)) does not add it to the PowerPoint. As a workaround, I decided to try to save myChart to disk, from where I could just add it to the PowerPoint that way.
So my question is really, How do I get my html image into my ReporteRs workflow? Either getting it saved to a disk, or getting it to be readable by ReporteRs would solve my problem.
This question is really the same as this one, but I'm using rCharts, specifically the example found here:
#if the packages are not already installed
install.packages('devtools')
require(devtools)
install_github('rCharts', 'ramnathv')
#code creates a radar chart using Highcharts
library(rCharts)
#create dummy dataframe with number ranging from 0 to 1
df<-data.frame(id=c("a","b","c","d","e"),val1=runif(5,0,1),val2=runif(5,0,1))
#muliply number by 100 to get percentage
df[,-1]<-df[,-1]*100
myChart <- Highcharts$new()
myChart$chart(polar = TRUE, type = "line",height=500)
myChart$xAxis(categories=df$id, tickmarkPlacement= 'on', lineWidth= 0)
myChart$yAxis(gridLineInterpolation= 'circle', lineWidth= 0, min= 0,max=100,endOnTick=T,tickInterval=10)
myChart$series(data = df[,"val1"],name = "Series 1", pointPlacement="on")
myChart$series(data = df[,"val2"],name = "Series 2", pointPlacement="on")
myChart
So if I try
> png(filename="~/Documents/name.png")
> plot(myChart)
Error in as.double(y) :
cannot coerce type 'S4' to vector of type 'double'
> dev.off()
I get that error.
I've looked into Highcharts documentation, as well as many other potential solutions that seem to rely on Javascript and phantomjs. If your answer relies on phantomjs, please assume I have no idea how to use it. webshot is another package I found which is even so kind as to include an install_phantomjs() function, but from what I could find, it requires you to turn your output into a Shiny object first.
My question is really a duplicate of this one, which is not a duplicate of this one because that is how to embed the html output in Rmarkdown, not save it as a file on the hard drive.
I also found this unanswered question which is also basically the same.
edit: as noted by #hrbrmstr and scores of others, radar charts are not always the best visualization tools. I find myself required to make one for this report.
The answer turned out to be in the webshot package. #hrbrmstr provided the following code, which would be run at the end of the code I posted in the question:
# If necessary
install.packages("webshot")
library(webshot)
install_phantomjs()
# Main code
myChart$save("/tmp/rcharts.html")
webshot::webshot("/tmp/rcharts.html", file="/tmp/out.png", delay=2)
This saves the plot to the folder as an html, and then takes a picture of it, which is saved as a png.
I can then run the ReporteRs workflow by using addImage(mydoc, "/tmp/out.png").
I want to be able to export the charts generated in my shiny application using rCharts to Image and PDF formats. Is there any provision in the rCharts library for that?
I have earlier used ggvis, It gives an option for resizing the chart in the browser and also an option to download the chart in HTML or PNG format. Anything similar to that?
Edit 1:
I'm using nvd3 and polyCharts as my charting libraries currently.
To download as image or pdf you can use a$exporting(enabled = T), assuming your chart is called a.
library(rCharts)
a <- hPlot(Pulse ~ Height, data = MASS::survey, type = "scatter", group = "Exer")
a$exporting(enabled = T)
a
To follow up on my comment above, I was a bit too quick to respond, as the htmlwidget::saveWidget() function is meant for widgets developed under the htmlwidgets.org framework. However, rCharts has a similar function:
library(rCharts)
a <- nPlot(Pulse ~ Height, data = MASS::survey, type = "scatterChart", group = "Exer")
a$save("demo.html", standalone=TRUE)
Where 'demo.html' is standalone html file. Creating a png is as simple as taking a screenshot. Note that you can also call this function in a shiny app.
For teaching purpose, I would like to make some R code appear line by line for an interactive course with students. I found the interactive console of slidify (ou have to run the video to see what it means at 4'55), but I would like to know if it is possible to hide/show the code or better, to show the code line by line (an option or an animation?).
I add the code I found as demo of the interactive console below but the fact that the code appears in an interactive console is not a high requirement for me, I just want to evaluate the code after having displayed it entirely (preferably without writing multiple slides for one exercise).
--- &interactive
## Interactive Console
``{r opts.label = 'interactive', results = 'asis'}
require(googleVis)
M1 <- gvisMotionChart(Fruits, idvar = 'Fruit', timevar = 'Year')
print(M1, tag = 'chart')
```
Near the end of this tutorial, there is a great explanation of how to sequentially reveal R code and he has posted the code as well.
http://zevross.com/blog/2014/11/19/creating-elegant-html-presentations-that-feature-r-code/