2016-02-18 29 views
1

我有一個隨機圖g,並需要將此圖分成兩個分離圖g1g2並附有規則。分割規則是二元矩陣E:if(E [i,j] = 1),然後將相應節點移動到圖g1,否則將相應節點移動到圖g2。分離後,我需要在屏幕上繪製三張圖。我使用矩陣E中的1來定義圖上的圖g1的節點位置(即mylayout1)。我的代碼如下所示。R:如何定義節點的佈局位置

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。

回答

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' 
    )