如何通过保存节点的位置和 ID 来绘制 igraph 子图?

How to plot the igraph subgraphs with saving the nodes' positions and ids?

我有一个 igraph G,我需要采样两个重叠的子图 G1、G2 并将它们绘制在具有相同布局的图上。

我的尝试如下:

library(igraph)
set.seed(1)
n <- 10
A <- matrix(sample(0:1, n * n, rep=TRUE), n, n)
diag(A) = 0
g <- graph_from_adjacency_matrix(A)

V(g)$names <- c(1:n)

id1 = sample(V(g), size = n %/% 2, replace = FALSE)
id2 = sample(V(g), size = n %/% 2, replace = FALSE)

g1 <- induced_subgraph(g, vids = id1)
g2 <- induced_subgraph(g, vids = id2)

V(g1)$names <- c(id1)
V(g2)$names <- c(id2)
#V(g)[id1]$color <- "red"
#V(g)[id2]$color <- "green"

par(mfrow=c(1,3))

layout <- layout.fruchterman.reingold(g)
plot(g, layout=layout, main="G")

plot(g1, layout = layout[-c(setdiff(1:n, id1)),], vertex.label=V(g)[id1], main="G1") 
plot(g2, layout = layout[-c(setdiff(1:n, id2)),], vertex.label=V(g)[id2], main="G2")

我的 ID 和标签问题。

问题。如何绘制 igraph 子图并保存节点的位置和 ID?

试试下面的代码

library(igraph)
set.seed(1)
n <- 10
A <- matrix(sample(0:1, n * n, rep = TRUE), n, n)
diag(A) <- 0
g <- graph_from_adjacency_matrix(A)


id1 <- sort(as.integer(sample(V(g), size = n %/% 2, replace = FALSE)))
id2 <- sort(as.integer(sample(V(g), size = n %/% 2, replace = FALSE)))

g1 <- induced_subgraph(g, vids = id1)
g2 <- induced_subgraph(g, vids = id2)


par(mfrow = c(1,3))

layout <- layout.fruchterman.reingold(g)

layout2 <- layout[id2, ]

plot(g, layout = layout, main = "G")
plot(g1, layout = layout[id1, ], main = "G1")
plot(g2, layout = layout[id2, ], main = "G2")