Thursday, October 25, 2012

Exploring R Local Server for Viewing d3 examples

Recently there was a great post on javascript and d3 for R users. The post showed a simple way to get a local server going using the python command (python -m SimpleHTTPServer 8888 &). A local server is needed to view the d3 examples in some cases. I was curious to see if I can view those using the internal R server.

I looked at googleVis package since they generate plots using the R local server. I tried to use the following code adapted from plot.gvis method in googlevis package and see if I could view the d3 examples.

# directory where d3 files were downloaded from github
setwd("~/javascript/d3github")

# piece of code adapted from plot.gvis method in googleVis package
tools:::startDynamicHelp()
## Error: server already running

googlevis.httpd.handler <- function(path, query, ...) {
    path <- gsub("^/custom/googleVis/", "", path)
    f <- sprintf("%s%s%s", getwd(), .Platform$file.sep, path)
    list(file = f, `content-type` = "text/html;charset=utf-8", `status code` = 200L)
}

env <- get(".httpd.handlers.env", asNamespace("tools"))
env[["googleVis"]] <- googlevis.httpd.handler

# viewing the html files through local server

baseURL <- sprintf("http://127.0.0.1:%s/custom/googleVis/examples/contour/contour.html", 
    tools:::httpdPort)
browseURL(baseURL)

baseURL <- sprintf("http://127.0.0.1:%s/custom/googleVis/examples/bubble/bubble.html", 
    tools:::httpdPort)
browseURL(baseURL)

baseURL <- sprintf("http://127.0.0.1:%s/custom/googleVis/examples/choropleth/choropleth.html", 
    tools:::httpdPort)
browseURL(baseURL)

The examples contour.html and bubble.html work fine. But choropleth.html does not render the colors properly. I don't know why that is happening.

However, if the server is already started with the python command, then from within R just the following commands work great

# server started with python command in command prompt in the directory
# ~/javascript/d3github python -m SimpleHTTPServer 8000

baseURL = "http://localhost:8000/examples/contour/contour.html"
browseURL(baseURL)

baseURL = "http://localhost:8000/examples/bubble/bubble.html"
browseURL(baseURL)

baseURL = "http://localhost:8000/examples/choropleth/choropleth.html"
browseURL(baseURL)

If anybody has other quicker ways of starting the R local server, please let me know.

1 comment:

  1. Thanks, Shankar, this is great! I'm not sure what the issues are with your approach, but I got a working version using the Rook package, and all the D3 examples I've tried have worked so far. Let me know if it works for you:
    http://civilstat.com/?p=861

    ReplyDelete