block by timelyportfolio b8c0706d498fa21b92d4

add interactivity to base R plots

Full Screen

One quick example of a workflow from base R plots to interactive SVG. An early pioneer in this is Duncan Temple Lang @duncantl with his XML and SVGAnnotation packages and his great book XML and Web Technologies for Data Sciences with R coauthored with Deborah Nolan. He demonstrates some examples with various base and grid plots here.

I think this is a very good example of amazing work just slightly ahead of its time. Now with d3, browser improvements, and javascript evolution, I think the time is right for this to progress and evolve into something powerful but expected.

There are infinite improvements that can be done to this example.

code.R

# for my friend Alex Bresler
#  adding interactivity to base R

library(SVGAnnotation)
library(pipeR)
library(htmltools)

svgPlot(
  # {} for closure to do multi-step plots
  {
    barplot(1:10)  # also works with grid - lattice | ggplot2
  }
) %>>%
  getNodeSet("//x:svg","x") %>>%
  ( saveXML(.[[1]]) ) %>>%
  HTML %>>%
  html_print


svgPlot(
  {
    plot(mpg ~ wt, mtcars)
  }
) -> doc

doc %>>%
  # get the points in the plot
  getNodeSet("//x:g/x:g[@clip-path='url(#clip1)']/x:path","x") %>>%
  (
    lapply(
      1:length(.)
      ,function(pt){
        addAttributes(
          .[[pt]]
          ,"data-tooltip" = rownames(mtcars)[pt]
          ,"class" = "dataPoint"
        )
      }
    )
  )
  
doc %>>% 
  saveXML %>>%
  HTML %>>%
  (
    tagList(
      .
      ,tags$script(
"
var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return '<strong>Model:</strong> <span style=\"color:red\">' + d3.select(this).attr(\"data-tooltip\") + '</span>';
  })

d3.select('body').select('svg')
  .call(tip);

d3.select('body').selectAll('.dataPoint')
  .style('pointer-events','all')
  .on('mouseover', tip.show)
  .on('mouseout', tip.hide)  

" %>>% HTML
      )
    )
  ) %>>%
  attachDependencies(
    list(
      htmlDependency(
        name="d3"
        ,version = "3.4"
        ,src = c(href="http://d3js.org")
        ,script = "d3.v3.min.js"
      )
      ,htmlDependency(
        name="d3tip"
        ,version = "0.6.3"
        # use timelyportfolio version since error d3caged
        ,src = c(href="http://timelyportfolio.github.io/rCharts_dimple/js")
        ,script = "d3.tip.v0.6.3.js"
      )
    )
  ) %>>%

  html_print