danielkrizian / rChartsDygraphs

An `rCharts` extension. Run `dygraphs` from R - interactive visualizations of time series using JavaScript and HTML canvas. See: http://dygraphs.com/ and
http://rcharts.io/
9 stars 10 forks source link

Layouts using Shiny #11

Open ramnathv opened 10 years ago

ramnathv commented 10 years ago

My apologies to be late to the party on layouts, but I got this inspiration just last night. Shiny has a full fledged HTML DSL for R that can be taken advantage of directly. Here is a simple example using the Shiny DSL to create two plots.

We first create two plots using rCharts. We set the width of all charts to 550 so that we can fit two in one column.

library(rCharts)
options(RCHART_WIDTH = 550)
r1 <- rPlot(mpg ~ wt, data = mtcars, type = 'point')
r2 <- rPlot(mpg ~ wt, color = 'am', data = mtcars, type = 'point')

Second, we write a small helper function that saves the chart html (just the div + script) as a character and runs it through shiny's HTML function to take care of escaping.

library(shiny)
rChart = function(x, id){
  x1 = paste(capture.output(x$print(id)), collapse = '\n')
  HTML(x1)
}

Next, we create a HTML page with the two charts using Shiny's DSL. Note that currently I am injecting the js/css assets manually, but it should be trivial to write a script that would do this automatically based on the library being used.

page = with(tags, html(
      link(href="http://netdna.bootstrapcdn.com/bootstrap/2.3.2/css/bootstrap.min.css", rel="stylesheet"),
      script(src="http://ramnathv.github.io/rCharts/libraries/widgets/polycharts/js/polychart2.standalone.js"),
  fluidRow(
    column(6, 
      rChart(r1, 'chart1')    
    ),
    column(6,
     rChart(r2, 'chart2')
    )
  )   
))

Finally, we save the generated HTML to a a tempfile and use the rstudio viewer to view it.

tf <- tempfile(fileext = ".html")
writeLines(as.character(h), con = tf)
rstudio::viewer(tf)

The nice thing about this approach is that it is very generic and we can take advantage of Shiny.

Let me know what you guys think. If you see value in this approach, I can abstract it out and create some wrappers within rCharts.

timelyportfolio commented 10 years ago

oh, that is a great thought. Let me know how I can help.

danielkrizian commented 10 years ago

wow, :+1: like the idea, many thanks Ramnath!

ramnathv commented 10 years ago

@danielkrizian After a brief conversation with @timelyportfolio I think this might be a fruitful avenue to explore. It adds a dependency on Shiny, but we can make it a suggested package, since it is only necessary when people want to create complex layouts.

Alternately, we can create our own version of the HTML DSL using this gist by Hadley. In any case, we would want to add updated versions of the column function to support Bootstrap 3.