在igraph中循环移除顶点并保持相同的布局坐标

问题描述

我希望能够根据顶点属性迭代删除顶点。我希望输出看起来像这样:

library(igraph)

g <- graph_from_literal(1-+2,2-+3,3-+4,4-+1,5)

V(g)$year <- c(1999,2000,2001,2002,2003)

kk <- layout_with_kk(g)

kk <- norm_coords(kk,xmin=-1,xmax = 1,ymin=-1,ymax = 1)

par(mfrow=c(2,2),mar=c(1,1,1))

# First plot
plot(g,vertex.label = V(g)$year,layout = kk*.5,frame = TRUE,main = "Original")

# Second plot
x <- as.numeric(which(V(g)$year <= 2000))

g2 <- induced_subgraph(g,V(g)$year <= 2000)

kk2 = kk[dput(x),]
#> c(1,2)

plot(g2,vertex.label = V(g2)$year,layout = kk2*.5,main = "2000 and earlier")

# third plot
x <- as.numeric(which(V(g)$year <= 2001))

g3 <- induced_subgraph(g,V(g)$year <= 2001)

kk2 = kk[dput(x),2,3)

plot(g3,vertex.label = V(g3)$year,main = "2001 and earlier")

# fourth plot
x <- as.numeric(which(V(g)$year <= 2002))

g4 <- induced_subgraph(g,V(g)$year <= 2002)

kk2 = kk[dput(x),3,4)

plot(g4,vertex.label = V(g4)$year,main = "2001 and earlier")

reprex package(v0.3.0)于2020-10-22创建

我的实际数据集很大,所以我想循环它,所以我不必写一百万次代码。我从here那里获得了一些启发-它使我有点接近,但距离还不够远,我的能力在这里处于末尾。

g <- graph_from_literal(1-+2,2003)

layout.old <- norm_coords(layout.kamada.kawai(g),xmin = -1,ymin = -1,ymax = 1)

maxyr <- max(V(g)$year)

dev.off()
#> null device 
#>           1

par(mfrow=c(2,1))

for(yr in seq(2001,maxyr,1)){
  gind <- induced_subgraph(g,V(g)$year <= yr)
  layout.new <- layout.kamada.kawai(g,coords=layout.old)
  plot(gind,vertex.label = V(gind)$year,layout = layout.new,frame = TRUE)
}

reprex package(v0.3.0)于2020-10-22创建

由此产生的输出将保持坐标并似乎产生一些迭代,但否则将无法达到我的期望(产生的输出类似于非循环示例)。

有人能对此有所启发吗?

解决方法

这些方面的情况如何。您可以将坐标“附加”到节点上,并在简短的自定义绘图功能中使用它们。

value

library(igraph)
#> 
#> Attaching package: 'igraph'
#> The following objects are masked from 'package:stats':
#> 
#>     decompose,spectrum
#> The following object is masked from 'package:base':
#> 
#>     union
g <- graph_from_literal(1-+2,2-+3,3-+4,4-+1,5)
V(g)$year <- c(1999,2000,2001,2002,2003)
xy <- norm_coords(
  layout_with_kk(g),xmin=-1,xmax = 1,ymin=-1,ymax = 1
)
V(g)$x <- xy[,1]
V(g)$y <- xy[,2]

myplot <- function(g,...) {
  plot(g,layout=cbind(V(g)$x,V(g)$y),rescale = FALSE,...)
}

layout(matrix(1:4,2,byrow=TRUE))
myplot(g,main="Original")
myplot(induced_subgraph(g,V(g)[year <= 2000]),main="2000 and earlier")
myplot(induced_subgraph(g,V(g)[year <= 2001]),main="2001 and earlier")
myplot(induced_subgraph(g,V(g)[year <= 2002]),main="2002 and earlier")

顺便说一下,程序包layout(1) tidygraph以与上述极为相似的方式将顶点坐标存储为顶点属性。