block by timelyportfolio 6210c87ec560d3af9765

rbokeh contour with MASS

Full Screen

code.R

#http://stats.stackexchange.com/questions/31726/scatterplot-with-contour-heat-overlay
library(MASS)  # in case it is not already loaded 
set.seed(101)
n <- 1000
X <- mvrnorm(n, mu=c(.5,2.5), Sigma=matrix(c(1,.6,.6,1), ncol=2))
## some pretty colors
library(RColorBrewer)
k <- 11
my.cols <- rev(brewer.pal(k, "RdYlBu"))
## compute 2D kernel density, see MASS book, pp. 130-131
z <- kde2d(X[,1], X[,2], n=50)

tf = tempfile()
png(tf, height = 400, width = 700, units = "px")
{
  plot(X, xlab="X label", ylab="Y label", pch=19, cex=.4)
  contour(z, drawlabels=FALSE, nlevels=k, col=my.cols, add=TRUE)
  abline(h=mean(X[,2]), v=mean(X[,1]), lwd=2)
  legend("topleft", paste("R=", round(cor(X)[1,2],2)), bty="n")
}
dev.off()


library(rbokeh)
(
  bp <- figure( width = 700, height = 400 ) %>%
    ly_points( X[,1], X[,2], size = 2 ) %>%
    ly_contour( z=z$z, x=z$x, y=z$y, nlevels = k, col = my.cols ) %>%
    ly_text( 
      x = min(pretty(X[,1]))
      ,y =  max(pretty(X[,2]))
      ,text = list(paste("R=", round(cor(X)[1,2],2)))
    )
)

library(htmltools)
library(gistr)
library(pipeR)

gist_auth(reauth=T)

tagList(
  HTML(base64::img(tf))
  ,rbokeh:::plot.BokehFigure(bp)
) %>>%
  html_print %>>% 
  (
    gist_create(
      list.files(dirname(.), recursive = T, full.names=T)
      ,description = "rbokeh contour with MASS"
    )
  )

rbokeh.js

HTMLWidgets.widget({

  name: 'rbokeh',

  type: 'output',

  initialize: function(el, width, height) {
    return {

    }
  },

  renderValue: function(el, x, instance) {

    if(x.isJSON == true) {
      x.all_models = JSON.parse(x.all_models);
    }

    Bokeh.logger.info("Realizing plot:")
    Bokeh.logger.info(" - modeltype: " + x.modeltype);
    Bokeh.logger.info(" - modelid: " + x.modelid);
    Bokeh.logger.info(" - elementid: " + x.elementid);

    if(x.r_debug == true) {
      console.log(x.all_models);
      console.log(JSON.stringify(x.all_models));
    }

    var dv = document.createElement('div');
    dv.id = x.elementid;
    dv.setAttribute("class", "plotdiv");
    el.appendChild(dv);

    Bokeh.load_models(x.all_models);
    var model = Bokeh.Collections(x.modeltype).get(x.modelid);
    var view = new model.default_view({model: model, el: '#' + x.elementid});
    Bokeh.index[x.modelid] = view;
  },

  resize: function(el, width, height, instance) {

  }

});