I am trying to create an interactive Sankey diagram in R using the networkD3
package as described at http://christophergandrud.github.io/networkD3/#sankey. My data is in the format of Discrete State Sequences(DSS). 1 row represents 1 event sequence. NAs represent that the sequence has ended. Recreating a sample of the data in R:
x1 <- c('06002100', '06002001', '06001304', '06002100')
x2 <- c('06002100', '06002001', 'NA', 'NA')
x3 <- c('06001304', '06002100', '06002001', 'NA')
test <- as.data.frame(rbind(x1,x2,x3))
networkd3 package requires data in the json form as given by:
URL <- paste0("https://cdn.rawgit.com/christophergandrud/networkD3/","master/JSONdata/energy.json")
Casting the sample data above in the required format would give me (test.json
):
{"nodes":[
{"name":"06002100"},
{"name":"06002001"},
{"name":"06001304"}
],
"links":[
{"source":0,"target":1,"value":3},
{"source":1,"target":2,"value":1},
{"source":2,"target":0,"value":2}
]}
Once the data is in the above format, I can use the following code to plot the sankey network.
library(networkD3)
library(jsonlite)
Energy <- fromJSON(txt = 'test.json') # Load the data
result <- as.data.frame(Energy)
sankeyNetwork(Links = Energy$links, Nodes = Energy$nodes, Source = "source", Target = "target", Value = "value", NodeID = "name", fontSize = 12, nodeWidth = 30)
I want to transform the DSS data that I have to the format required by networkD3. Is there a direct way to do this?
networkD3 examples page mentions that I can use igraph
package to create network graph data that can be plotted with networkD3. Unfortunately I couldn't find good examples for that.