在图形上将所有节点连接在一起

Connecting All Nodes Together on a Graph

我有以下网络图:

library(tidyverse)
library(igraph)


set.seed(123)
n=5
data = tibble(d = paste(1:n))

relations = data.frame(tibble(
  from = sample(data$d),
  to = lead(from, default=from[1]),
))

graph = graph_from_data_frame(relations, directed=T, vertices = data) 

V(graph)$color <- ifelse(data$d == relations$from[1], "red", "orange")

plot(graph, layout=layout.circle, edge.arrow.size = 0.2)

我想将每个节点连接到此图上的每个节点 - 我可以通过重新定义“关系”数据框来手动完成此操作:

relations_1 = data.frame("from" = c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5), "to" = c(2,3,4,5,1,3,4,5,1,2,4,5,1,2,3,5,1,2,3,4))

然后,我可以重新运行网络图:

graph = graph_from_data_frame(relations_1, directed=T, vertices = data) 

V(graph)$color <- ifelse(data$d == relations_1$from[1], "red", "orange")

plot(graph, layout=layout.circle, edge.arrow.size = 0.2)

谢谢!

您可以使用 complete 更新 relations,然后过滤掉 from 等于 to 的行,这会给出从节点到自身的箭头.

relations <- relations %>% 
  complete(from, to) %>% 
  dplyr::filter(from != to)

使用igraph::make_full_graph的解决方案:

relations %>%
  with(union(from,to)) %>%
  {
    G <- make_full_graph(length(.), directed = TRUE)
    V(G)$name <- .
    G
  }

如果您偏离 graph,您可以使用 add_edges + get.adjacency

尝试以下代码
graph %>%
    add_edges(c(t(which(`diag<-`(get.adjacency(., sparse = FALSE), 1) != 1, arr.ind = TRUE))))

添加所有缺失的边,同时保留原始 graph 对象的属性,您将看到