Difficulty reproducing stacked bar graph in R using dygraphs - r

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

Related

Trying to get multiple tooltip/hover text values using ChoroplethrZip/Plotly

I'm trying to draw a zip code level choropleth using the choroplethrZip package, and Plotly to get hover text/tooltips. choroplethrZip plots are ggplot2 objects, so I can make a zip code choropleth using the zip_choropleth function, and then use the ggplotly() function of plotly to render a choropleth where the pre-defined bins are the hover text. I'd like for the hover text to be the "region" column in my data frame, as well as the "value" column. The tooltip argument of ggplotly displays the aesthetic mappings, but choroplethrZip doesn't let me specify those. I tried adding them by using
+geom_blank(aes(text=region))
, but I get the same result, the hover text is just the bin that the zip belongs to.
Example code:
library(choroplethrZip)
library(choroplethr)
library(choroplethrMaps)
library(plotly)
library(ggplot2)
df <- get_zip_demographics(endyear= 2013, span=5)
colnames(df)[2] <- c("value")
zipplot <- zip_choropleth(df, state_zoom = "alabama")
ggplotly(zipplot)
Edited to add a library necessary for the code example to work. Also, the choroplethrZip package isn't on CRAN, so here is a link with installation instructions:
https://github.com/arilamstein/choroplethrZip

How to save a plot as image on disk from Viewer in RStudio?

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

Export the graph generated by rCharts in shiny application

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.

save image of d3heatmap in a file

I am using d3heatmap package in R for to draw heatmaps. When I use it in Rstudio, I can save images that it produces by choosing save image from the viewer menu. I am wondering how I can save the heatmap to a file in an Rscript. Apparently, png(filename) does not work.
A potential approach is using htmlwidgets and save it in html form only since the d3heatmap returns object of class "d3heatmap" "htmlwidget"
EG.
library(htmlwidgets)
data(mtcars)
map <- d3heatmap(mtcars, scale = "column")
saveWidget(map, "test.html")

Synchronization of dygraph in R not working

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.

Resources