R:如何定义节点

时间:2016-02-18 01:38:09

标签: r layout graph igraph

我有一个随机图表g,需要将此图表拆分为两个独立的图表g1g2。拆分规则是二进制矩阵E:if(E [i,j] = 1)然后将相应的节点移动到图形g1,否则将相应的节点移动到图形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'
     )

请问某人如何为第二张图mylayout2定义g2?我想使用mylayout中节点的原始位置。解决方案之一可能是再次使用矩阵E。不幸的是,我无法弄清楚如何在矩阵E中使用0。

1 个答案:

答案 0 :(得分: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'
     )