VisNetwork from IGraph - Can't Implement Clust

2019-03-02 07:09发布

问题:

I am starting to use the package called visNetworkand I feel like it has a ton of potential for User-Interface use in the future.

There are few things that I am having trouble with though. I have created an igraph and have also applied a clustering algorithm to that specifically the fastgreedy algorithm.

Example Code Provided:

B = matrix( 
 c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 47, 3, 0, 3, 0, 1, 10, 13, 5,
0, 3, 19, 0, 1, 0, 1, 7, 3, 1,
0, 0, 0, 3, 0, 0, 0, 0, 0, 0,
0, 3, 1, 0, 32, 0, 0, 3, 2, 1,
0, 0, 0, 0, 0, 2, 0, 0, 0, 0,
0, 1, 1, 0, 0, 0, 2, 1, 1, 0,
0, 10, 7, 0, 3, 0, 1, 90, 12, 4, 
0, 13, 3, 0, 2, 0, 1, 12, 52, 4, 
0, 5, 1, 0, 1, 0, 0, 4, 4, 18), 
 nrow=10, 
 ncol=10)
 colnames(B) <- c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J")
 rownames(B) <- c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J")

g96e = t(B) %*% B

i96e = graph.adjacency(g96e, mode = "undirected", weighted = TRUE, diag=FALSE)

Then I applied the clustering algorithm to this:

V(i96e)$label = V(i96e)$name
V(i96e)$label.color = rgb(0,0,.2,.8)
V(i96e)$label.cex = .1
V(i96e)$size = 2
V(i96e)$color = rgb(0,0,1,.5)
V(i96e)$frame.color = V(i96e)$color
fc<-fastgreedy.community(i96e, merges=TRUE, modularity=TRUE,
                 membership=TRUE, weights=E(i96e)$weight)
colors <- rainbow(max(membership(fc)))

Now using the visNetwork package, I want to change the colors of the nodes so that it matches the colors from the clustering algorithm. My issue is I do not know how to change the color of the nodes.

visNetwork Example:

library(visNetwork)
visIgraph(i96e, idToLabel = TRUE, layout = "layout_nicely")%>%
visNodes(size = 10) %>%
visOptions(highlightNearest = TRUE, 
         nodesIdSelection = TRUE)     

I want to have the color of the nodes be the same as the clusters.

Any help would be great, thanks!

回答1:

Here is a solution. Just build the plain graph with igraph and then make the cosmetic changes using visNetwork:

Code:

 i96e = graph.adjacency(g96e, mode = "undirected", weighted = TRUE,    diag=FALSE)
 fc<-fastgreedy.community(i96e, merges=TRUE, modularity=TRUE,
                     membership=TRUE, weights=E(i96e)$weight)
 library (visNetwork)
 dummy <- toVisNetworkData(i96e)
 my.edges <- dummy$edges
 my.nodes <- dummy$nodes
 my.nodes$groups <- fc$membership
 my.nodes$color.background <- c("red", "blue", "green" ,"yellow")[my.nodes$groups]
 my.nodes$color.border <- c("red", "blue", "green" ,"yellow")[my.nodes$groups]
 my.nodes$size = 5
 my.edges$color <- "black"
 visNetwork(my.nodes, my.edges)%>%
 visIgraphLayout()