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

# piece of code adapted from plot.gvis method in googleVis package
## 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("", 

baseURL <- sprintf("", 

baseURL <- sprintf("", 

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"

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

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

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: