Sankey diagram with R, rCharts, d3


/ Published in: R
Save to your folder(s)

My first attempt at a Sankey diagram in R, using rCharts and timelyportfolio's work


Copy this code and paste it in your HTML
  1. # sankey chart using d3 plugin for rCharts and the igraph library
  2.  
  3. require(rCharts)
  4. require(igraph)
  5.  
  6. # these are our vertices/nodes/end points/stages/categories/classes/whatever
  7. nodes = c("PhD",
  8. "Career Outside Science",
  9. "Early Career Researcher",
  10. "Research Staff",
  11. "Permanent Research Staff",
  12. "Professor",
  13. "Non-Academic Research")
  14.  
  15. # the chart is basically a graph
  16. g <- graph(c(1, 2, 1, 3, 3, 4, 3, 7, 4, 2, 4, 5, 4, 6, 4, 7))
  17. E(g)$weights <- c(53., 47., 30., 17., 22.5, 3., .5, 4.)
  18.  
  19. # convert to data frame with appropriate node names
  20. edgelist <- get.data.frame(g)
  21.  
  22. # name columns as what is expected by plugin
  23. colnames(edgelist) <- c("source", "target", "value")
  24. edgelist$source <- lapply(edgelist$source, FUN = function(x) {nodes[x]})
  25. edgelist$target <- lapply(edgelist$target, FUN = function(x) {nodes[x]})
  26.  
  27. # now we plot
  28. sankeyPlot <- rCharts$new()
  29. sankeyPlot$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey/libraries/widgets/d3_sankey')
  30. sankeyPlot$set(
  31. data = edgelist,
  32. nodeWidth = 15,
  33. nodePadding = 25,
  34. layout = 32,
  35. width = 800,
  36. height = 500
  37. )
  38. sankeyPlot

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.