绘制没有链接的网络:两个节点之间存在的键的权重越大,图中将它们分开的距离越小

Plot network without links: the greater the weight of the bond that exists between two nodes, the smaller the distance that separates them in the plot

以下是取自 igraph 包的示例:

library(igraph)
actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David", "Esmeralda"))
relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David","David", "Esmeralda"),
                        to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"),
                        friendship=c(4,5,5,2,1,1))
g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors)

图表的情节如下:

不过,我想得到一个不同的情节。目的是提高图形的质量和美感,例如使用 ggplot2(或其他我不知道的解决方案)。

绘图不应包含节点之间的 links:节点之间应该越近,它们之间存在的 link 的权重越大。节点应该有自己的标签(如上图所示)并且它们的大小应该与数据帧 df.

的变量 p 的值成比例
> dput(df)
structure(list(nodes = c("Alice", "Bob", "Cecil", "David", "Esmeralda"
), p = c(4, 3, 2, 2, 1)), class = "data.frame", row.names = c(NA, 
-5L))

> df
      nodes p
1     Alice 4
2       Bob 3
3     Cecil 2
4     David 2
5 Esmeralda 1

更新

也许你可以使用visNetwork

library(visNetwork)

nodes <- transform(
  setNames(df, c("label", "value")),
  id = seq_along(label)
)

edges <- transform(
  relations,
  from = match(from, nodes$label),
  to = match(to, nodes$label),
  length = prod(friendship) / friendship
)

visNetwork(nodes, edges) %>%
  visEdges(hidden = TRUE)

这给出了


上一个答案

也许你可以试试下面的代码

g %>%
  set_edge_attr(name = "width", value = E(.)$friendship) %>%
  set_vertex_attr(name = "size", value = 10 * with(df, p[match(nodes, names(V(.)))])) %>%
  plot()

一个简单的解决方案是将边值 friendship 视为边 weight。在内部,这些权重依次馈入 igraph 的标准布局算法(?layout_nicely?layout_with_fr 参见 weights 参数):

E(g)$weight <- E(g)$friendship^2     # squaring increases the observed effect
plot(g)

或单行:

plot(g, layout = layout_with_fr(g, weights = E(g)$friendship^2)

要省略链接,您只需将边缘颜色设置为白色即可:

plot(g, 
     layout = layout_with_fr(g, weights = E(g)$friendship^2, 
     edge.color = 'white'))

或者在更优雅的解决方案中预先计算布局并完全删除链接。

l <- layout_with_fr(g, weights = E(g)$friendship^2)
g <- delete.edges(g, which(E(g)$friendship > 0))
plot(g, layout = l)