【问题标题】:draw multiple discrete networks in R using igraph使用 igraph 在 R 中绘制多个离散网络
【发布时间】:2023-03-29 22:33:02
【问题描述】:

我想要绘制一组简单的方向关系(父->子)。我的数据的结构使得有许多离散的子网络。这是一些看起来像我的假数据。

require(igraph)
parents<-c("A","A","C","C","F","F","H","I")
children<-c("B","C","D","E","G","H","I","J")
begats<-data.frame(parents=parents,children=children)
graph_begats<-graph.data.frame(begats)
plot(graph_begats)

虚假数据中有两个不同的子网络,每个子网络严格来说都是父子血统。我需要在同一个窗口(理想情况下是相同的顶点坐标系)中将两个谱系绘制为树网络。我曾尝试使用 layout.reingold.tilford(),但我最多只能绘制其中一棵树,所有其他顶点都绘制在根顶点之上,就像这样。

lo<-layout.reingold.tilford(graph_begats,root=1)
plot(graph_begats,layout=lo)

对任意数量的离散谱系执行此操作有什么想法吗?

【问题讨论】:

  • 如果我能弄清楚如何 A) 计算数据集中离散谱系的数量,并且 B) 将每个顶点分配给它的谱系,我将是解决我的问题的 75%问题。
  • 将网络拆开,使用clusters()decompose.graph(),然后分别计算每个布局,然后通过移动其中一个布局矩阵来合并它们。
  • 是的! decompose.graph() 是我需要的。仍在进行矩阵转换,但我正在实现目标。
  • 为了使用layout.reingold.tilford() 正确获取树布局,我需要一种识别根节点的方法。我通过获取topological sort() 函数返回的第一个顶点来实现这一点,如topological.sort(theGraph)[1]。这对于我的示例数据中的子图不是必需的,但在实际数据中通常是必需的。

标签: r tree igraph


【解决方案1】:

因此,正如我在上面的评论中提到的,一种解决方案是分别为每个组件计算布局。它相当简单,即使需要一些代码才能正确完成。下面的代码应该适用于任意数量的组件。拓扑排序中的第一个顶点作为每棵树的根节点。

require(igraph)

## Some data
parents <- c("A", "A", "C", "C", "F", "F", "H", "I")
children <- c("B", "C", "D", "E", "G", "H", "I", "J")
begats <- data.frame(parents=parents, children=children)
graph_begats <- graph.data.frame(begats)

## Decompose the graph, individual layouts
comp <- decompose.graph(graph_begats)
roots <- sapply(lapply(comp, topological.sort), head, n=1)
coords <- mapply(FUN=layout.reingold.tilford, comp,
                 root=roots, SIMPLIFY=FALSE)

## Put the graphs side by side, roots on the top
width <- sapply(coords, function(x) { r <- range(x[, 1]); r[2] - r[1] })
gap <- 0.5
shift <- c(0, cumsum(width[-length(width)] + gap))
ncoords <- mapply(FUN=function(mat, shift) {
  mat[,1] <- mat[,1] - min(mat[,1]) + shift
  mat[,2] <- mat[,2] - max(mat[,2])
  mat
}, coords, shift, SIMPLIFY=FALSE)

## Put together the coordinates for the original graph,
## based on the names of the vertices
lay <- matrix(0, ncol=2, nrow=vcount(graph_begats))
for (i in seq_along(comp)) {
  lay[match(V(comp[[i]])$name, V(graph_begats)$name),] <- ncoords[[i]]
}

## Plot everything
par(mar=c(0,0,0,0))
plot(graph_begats, layout=lay)

【讨论】:

  • 非常感谢,Gabor。就是这样!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多