简体   繁体   English

如何使用预定义布局保存 igraph object 的边列表?

[英]How to save the edge list of igraph object with the predefined layout?

I have read the R igraph - save layout?我已阅读R igraph - 保存布局? , but in my case it is requared to save positions of begin's and end's edges into a file with the edge list together. ,但在我的例子中,需要将开始边缘和结束边缘的位置与边缘列表一起保存到一个文件中。

I have a tree igraph object and predefined mylayout layout on the plane.我在平面上有一个tree igraph object 和预定义的mylayout布局。

tree <- make_tree(5, 2, mode = "undirected")
mylayout <- matrix(c(1, 2, 0, 3, 2, 
                     1, 2, 0, 2, 3), ncol=2)

I have add a new attribute name我添加了一个新的属性name

tree <- make_tree(5, 2, mode = "undirected") %>% 
            set_vertex_attr("name", value = seq(1:vcount(tree)))

and I get the edge list of graph via the get.edgelist() function, and I am going to use name attribute:我通过get.edgelist() function 得到图的边列表,我将使用name属性:

   df1 <- data.frame(V1 = get.edgelist(tree)[,1], 
                  V2 = get.edgelist(tree)[,2], 
#           V1_x = mylayout[as.integer(names(V(tree))), 1],
#           V1_y = mylayout[as.integer(names(V(tree))), 2],
#           V2_x = mylayout[, 1],
#           V2_y = mylayout[, 2],
            stringsAsFactors = FALSE)

Question.问题。 How to match the nodes positions with the begin's and end's positions of edges?如何将节点位置与边缘的开始和结束位置相匹配?

You can try this你可以试试这个

get.data.frame(tree) %>%
  cbind(
    split(
      data.frame(mylayout)[match(unlist(.), 1:nrow(mylayout)), ],
      c(col(.))
    )
  )

which gives这使

  from to 1.X1 1.X2 2.X1 2.X2
1    1  2    1    1    2    2
2    1  3    1    1    0    0
3    2  4    2    2    3    2
4    2  5    2    2    2    3

I don't know if there's an existing way to do this, but it's not too much work to write a helper function to do this我不知道是否有现有的方法可以做到这一点,但是写一个帮助程序 function 来做这件事并不太费力

join_layout <- function(g, layout) {
  edges <- as_edgelist(g)
  idx1 <- match(edges[,1], V(g)$name)
  idx2 <- match(edges[,2], V(g)$name)
  result <- cbind(data.frame(edges),
        layout[idx1, ],
        layout[idx2, ]
  )
  names(result) <- c("V1", "V2", "V1_x", "V1_y", "V2_x","V2_y")
  result
}

Basically we use match() to match up the vertex names to rows in the layout matrix.基本上我们使用match()将顶点名称与布局矩阵中的行匹配。 You call it by passing in the igraph object and your layout你通过传入igraph object 和你的布局来调用它

join_layout(tree, mylayout)
#   V1 V2 V1_x V1_y V2_x V2_y
# 1  1  2    1    1    2    2
# 2  1  3    1    1    0    0
# 3  2  4    2    2    3    2
# 4  2  5    2    2    2    3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM