R:如何定义节点的布局位置

R: how to define layout position of nodes

我有一个随机图 g,需要根据规则将此图拆分为两个单独的图 g1g2。拆分规则为二元矩阵E:if (E[i,j]=1) then move the corresponding node to the graph g1, else move the corresponding node to g2.分离后我需要在屏幕上绘制三个图形。我使用矩阵 E 中的 1 来定义图 g1 中节点在图上的位置(即 mylayout1)。我的代码如下所示。

library(igraph)
set.seed(42)
n <- m <- 5
B <- matrix(sample(0:255, (n*m)^2, replace=T), nrow = n*n, ncol = m*m)
g <- graph.adjacency(B, weighted=TRUE, mode="undirected", diag=FALSE)
V(g)$name <- as.character(1:(n*m))
E <- matrix(sample(0:1, n*m, replace=T), nrow = m, ncol = n)

# split into two graphs, if (E[i,j]=1) then the node move to g1, else to g2 

vsubgraph <- c(1:length(E))*E
vsubgraph <- vsubgraph[vsubgraph != 0]

g1 <- induced_subgraph(g, vsubgraph)
g2 <- induced_subgraph(g, setdiff(V(g), vsubgraph))

V(g)[vsubgraph]$color <- "green"
V(g)[setdiff(V(g), vsubgraph)]$color <- "yellow"

V(g1)$name <- vsubgraph 
V(g2)$name <- setdiff(V(g), vsubgraph)

V(g1)$color <- "green"
V(g2)$color <- "yellow"

par(mfrow=c(1,3))

# create layout
cx <-rep(1:n, each = m)
cy <-rep(c(1:m), times = n)

mylayout <- as.matrix(cbind(cx, -cy))

plot(g, layout=mylayout,
          vertex.shape = "square",  
          vertex.label = V(g)$name, 
          edge.label.cex=.75,
          xlab='Original graph'
     )

cx <- cx * E
cy <- cy * E

cx <- cx[cx != 0]
cy <- cy[cy != 0]

mylayout1 <- as.matrix(cbind(cx, -cy))

plot(g1, layout=mylayout1,
          vertex.shape = "square",  
          vertex.label = V(g)$name, 
          edge.label.cex=.75,
          xlab='1st graph'
     )
plot(g2, #layout=mylayout2,
          vertex.shape = "square",  
          vertex.label = V(g)$name, 
          edge.label.cex=.75,
          xlab='2nd graph'
     )

有人可以告诉我如何为第二个图 g2 定义 mylayout2 吗?我想使用 mylayout 中节点的原始位置。解决方案之一可能是再次使用矩阵 E 。不幸的是,我不知道如何使用矩阵 E.

中的 0

一种可能的方法是:

opE <- ifelse(E == 0, 1, 0)

cx <-rep(1:n, each = m)
cy <-rep(c(1:m), times = n)

cx <- cx * opE
cy <- cy * opE

cx <- cx[cx != 0]
cy <- cy[cy != 0]

mylayout2 <- as.matrix(cbind(cx, -cy))

plot(g2, layout=mylayout2,
          vertex.shape = "square",  
          vertex.label = V(g)$name,
          edge.label.cex=.75,
          xlab='2nd graph'
     )