在绘图框中使用相同的坐标和相同的位置绘制两个igraph网络

时间:2017-09-10 10:31:18

标签: r plot igraph

我正在尝试绘制一个随时间变化的网络。网络以一定数量的节点和边缘开始,每次移除一些节点和边缘。

我希望能够绘制网络,以便节点位于每个节点的相同位置。但是,当我尝试这个。有时候节点会在图框中移位,即使彼此的关系是相同的。

我正在将网络变成一个gif,所以即使很小的变化也很烦人。我认为当大部分节点被移除但我不确定时可能会发生这种变化。

下面的代码使用ER图说明了这一点。

library(igraph); library(dplyr)

#generate random graph
set.seed(500)
RandomGraph <- sample_gnm(1000, 2500)

#name nodes
V(RandomGraph)$name <- paste0("Node", 1:1000)

#Get the coordinates of the Nodes
Coords <- layout_with_fr(RandomGraph) %>% 
  as_tibble %>%
    bind_cols(data_frame(names = names(V(RandomGraph))))

#Delete random vertices
deletevertex <-sample( V(RandomGraph)$name, 400)

RandomGraph2 <-delete.vertices(RandomGraph, deletevertex)

#get the coordinates of the remaining Nodes
  NetCoords <- data_frame(names = names(V(RandomGraph2))) %>%
    left_join(Coords, by= "names")

#plot both graphs

RandomGraph%>% 
  plot(.,vertex.size=.8, edge.arrow.size=.4, vertex.label = NA, layout = as.matrix(Coords[,1:2]))

RandomGraph2%>% 
  plot(.,vertex.size=.8, edge.arrow.size=.4, vertex.label = NA, layout = as.matrix(NetCoords[,2:3]))

#They nodes have the same relationship to each other but are not laid out in the same position in the frame

正如您所看到的,这些图表将节点相对于彼此放置在相同的位置,但不是相对于框架。

如何修改情节位置。

2 个答案:

答案 0 :(得分:2)

plot.igraph默认重新调整每个轴(在x和y上从-1到+1)。

您只需将其关闭:rescale = F,然后明确设置适当的xlimylim值。

您的示例代码..

RandomGraph%>% 
  plot(.,vertex.size=.8, edge.arrow.size=.4, vertex.label = NA, layout = as.matrix(Coords[,1:2]),rescale=F,xlim=c(-25,30),ylim=c(-20,35))

RandomGraph2%>% 
  plot(.,vertex.size=.8, edge.arrow.size=.4, vertex.label = NA, layout = as.matrix(NetCoords[,2:3]),rescale=F,xlim=c(-25,30),ylim=c(-20,35))

答案 1 :(得分:2)

问题在于

identical(range(Coords[1]), range(NetCoords[2]))
# [1] FALSE

由于igraph在绘图之前将坐标标准化为介于-1和1之间的范围,因此与NetCoords相比,Coords的坐标略有不同。我只是预先计算所有节点的标准化坐标

coords_rescaled <- sapply(Coords[-3], function(x) -1+((x-min(x))*2)/diff(range(x)))
rownames(coords_rescaled) <- Coords$names

然后分配规范化坐标(或所需子集)并设置已建议的rescale=FALSE(如@jul):

par(mfrow=c(1,2), mar=c(1,.5,1,.5))
RandomGraph%>% 
  plot(.,edge.arrow.size=.4, layout = coords_rescaled, rescale=F);box()
RandomGraph2%>% 
  plot(.,edge.arrow.size=.4, layout = coords_rescaled[NetCoords$names, ], rescale=F);box()
相关问题