Reputation: 431
> nodes1 <- c('A','B','C')
> nodes2 <- c('S','C','B')
> values <- c(1.0,0.45,0.44)
> data <- data.frame(nodes1,nodes2,values)
The data frame above has three columns. The first two columns denote the nodes and the third column denotes the weight between them. This is an undirected graph. I looked up on the networkD3
package documentation but could not find a simple way to do it.
Thank You in Advance !
Upvotes: 1
Views: 703
Reputation: 8848
To use the forceNetwork()
function in networkD3
, you need one data frame for the links and one data frame for the nodes. Using your vectors above, you can create appropriate data frames and pass them to forceNetwork()
like this...
library(networkD3)
nodes <- data.frame(id = unique(c(nodes1, nodes2)), group = 1)
links <- data.frame(source = match(nodes1, nodes$id) - 1,
target = match(nodes2, nodes$id) - 1,
value = values)
forceNetwork(Links = links, Nodes = nodes, Source = 'source', Target = 'target',
Value = 'value', NodeID = 'id', Group = 'group')
The nodes
data frame needs one column for the 'id' or name of each node, and one column for the group of each node (which you can just set to 1
if there they are not grouped). After running the code above, the nodes
data frame looks like this...
id group
1 A 1
2 B 1
3 C 1
4 S 1
The links
data frame needs 1 row for each link/edge, and one column for the 'source' of the link, one column for the 'target' of each link, and one column for the 'value' of each link. The 'source' and 'target' values equal the index of the node in the nodes
data frame that they refer to, but they must be zero-indexed to work with the underlying JavaScript. After running the code above, the links
data frame looks like this...
source target value
1 0 3 1.00
2 1 2 0.45
3 2 1 0.44
Upvotes: 1
Reputation: 1030
I think you could use igraph, the width of an edge is determined by the value in column in the dataframe.
library("igraph")
graph <- make_graph(t(data[,c("nodes1" , "nodes2")]), directed = F)
E(graph)$weight <- data$values
plot.igraph(graph, edge.width=E(graph)$weight)
Upvotes: 1