R visNetwork + igraph加权网络可视化与visEdges

R visNetwork + igraph加权网络可视化与visEdges

问题描述:

我有一个非常简单的问题关于结合igraph与visNetwork。我想用visEdges(value = E(graph)$ weight)加权边缘,但这不起作用。 这里是一个玩具的例子来说明这个问题:如果我使用R visNetwork + igraph加权网络可视化与visEdges

test.gr %>% 
    visIgraph(layout = "layout_in_circle") %>% 
    visEdges(value = E(test.gr)$weight) 

 test 
    [,1] [,2] [,3] [,4] [,5] 
[1,] 0 1 3 7 1 
[2,] 4 0 8 9 5 
[3,] 10 3 0 8 3 
[4,] 5 1 5 0 7 
[5,] 8 2 7 4 0 

library(igraph); library(visNetwork) 

test.gr <- graph_from_adjacency_matrix(test, mode="undirected", weighted=T) 

如果我现在试着想象它作为一个加权图,它不会绘制它

test.gr %>% 
    visIgraph(layout = "layout_in_circle") %>% 
    visEdges(value = 10) 

相反,我得到一个情节:

enter image description here

但这当然不是我想要的。根据E(test.gr)$ weigth我想要不同的边缘宽度。

你能告诉我如何做到这一点吗?

使用visNodesvisEdges您可以为所有节点和边缘设置全局选项。例如, visNodes(shape = "square"),你的所有节点都是正方形。你知道这不是设置单个边缘宽度的正确路线。

要实现您想要的功能,您可以将igraph对象转换为visNetwork -list。然后,您可以添加名为“值”的“预期”列。然后visNetwork将使用该列来赋予边缘权重。

也许这不是最好的解决方案,但它的工作原理。

test <- as.matrix(read.table(header = FALSE, text = " 
    0 1 3 7 1 
    4 0 8 9 5 
    10 3 0 8 3 
    5 1 5 0 7 
    8 2 7 4 0")) 

library(igraph) 
library(visNetwork) 

## make igraph object 
test.gr <- graph_from_adjacency_matrix(test, mode="undirected", weighted=T) 

## convert to VisNetwork-list 
test.visn <- toVisNetworkData(test.gr) 
## copy column "weight" to new column "value" in list "edges" 
test.visn$edges$value <- test.visn$edges$weight 

test.visn$edges 
# from to weight value 
# V1 V2  4  4 
# V1 V3  10 10 
# V1 V4  7  7 
# V1 V5  8  8 
# V2 V3  8  8 
# V2 V4  9  9 
# V2 V5  5  5 
# V3 V4  8  8 
# V3 V5  7  7 
# V4 V5  7  7 

visNetwork(test.visn$nodes, test.visn$edges) %>% 
    visIgraphLayout(layout = "layout_in_circle") 

我们得到以下图表:

enter image description here

请让我知道这是否是你想要的。