christophergandrud / networkD3

D3 JavaScript Network Graphs from R
http://christophergandrud.github.io/networkD3
650 stars 269 forks source link

Creating list for trees with an edgelist #224

Open chendaniely opened 6 years ago

chendaniely commented 6 years ago

Here's a snippet of code when you have an edgelist and want to use it to create one of the tree diagrams (e.g., radialNetwork)

library(data.tree)
library(networkD3)

pokemon <- structure(list(name = structure(c(5L, 4L, 6L, 1L, 7L, 3L, 2L), .Label = c("Eevee", 
"Flareon", "Jolteon", "Pichu", "Pikachu", "Raichu", "Vaporeon"
), class = "factor"), meta.contruct = structure(c(3L, 1L, 4L, 
1L, 2L, 2L, 2L), .Label = c("", "Eevee", "Pichu", "Pikachu"), class = "factor")), .Names = c("name", 
"meta.contruct"), class = "data.frame", row.names = c(NA, -7L
))

tree <- FromDataFrameNetwork(pokemon[, 1:2])
pokelist <- ToListExplicit(tree, unname = TRUE)

radialNetwork(pokelist)

would this be good to put in the docs for radialNetwork?

cjyetman commented 6 years ago

In the current dev version of networkD3, treeNetwork supersedes radialNetwork and the other tree network plotting functions. treeNetwork should handle an 'edgelist' as in your example, though your example does expose a problem when a root node is not specified in the data. Modifying your example somewhat, the following does work...

pokemon <- read.csv(header = T, text = "
name,meta.contruct
root,
Pikachu,Pichu
Pichu,root
Raichu,Pikachu
Eevee,root
Vaporeon,Eevee
Jolteon,Eevee
Flareon,Eevee
")

treeNetwork(pokemon, direction = "radial", 
            cols = c(nodeId = "name", parentId = "meta.contruct"))