如何使用其他输入在igraph中为R绘制社区多边形?

问题描述

能帮我吗?

我喜欢用igraph为R绘制网络。一个不错的功能是在给定算法检测到的社区周围绘制多边形

使用igraph内置的一种社区检测算法时,这非常简单。就像在此示例中具有随机二分图一样:

library(igraph)
graph <- sample_bipartite(10,10,p = 0.5)
graph
graph.lou = cluster_louvain(graph)
graph.lou$membership
length(graph.lou$membership)
plot(graph.lou,graph)

但是如何使用另一种输入来绘制这些多边形?

例如,我通常使用R的bipartite包来计算模块化,因为它具有其他更适合于双模网络的算法。

因此,我尝试将二分体的输出用作在igraph中绘制社区多边形的输入。如以下示例所示:

library(bipartite)
matrix <- as_incidence_matrix(graph)
matrix
matrix.bec = computeModules(matrix,method = "Beckett")
modules <- module2constraints(matrix.bec)
modules
length(modules)
plot(modules,graph)

computeModules函数输出中,我可以使用module2constraints函数提取具有社区成员身份的向量。当我尝试将其用作绘图输入时,出现以下错误消息:

Error in xy.coords(x,y,xlabel,ylabel,log) : 
  'x' and 'y' lengths differ

是否可以使用bipartiteigraph输出,以便在社区周围自动绘制多边形?

我研究了文档,在StackOverflow上进行了搜索,尝试了一些技巧,但没有找到解决方法

非常感谢您!

解决方法

在另一个question的帮助下,我已经找到了解决方案!

实际上,在R的igraph中的社区周围绘制多边形的另一种方法是使用函数mark.groups的参数plot

但是,此参数仅接受社区成员身份列表。因此,如果要使用 vector 格式的软件包bipartite的输出与igraph对象一起使用,则需要将其转换为列出

原始问题中描述的向量 modules中包含的信息需要补充顶点名称,并首先成为数据框架,然后成为列表:

number <- seq(1:10)
row <- "row"
rowlabels <- paste(row,number,sep = "")
column <- "col"
columnlabels <- paste(column,sep = "")

matrix <- matrix(data = rbinom(100,size=1,prob=0.5),nrow = 10,ncol = 10,dimnames = list(rowlabels,columnlabels))

library(bipartite)
matrix.bec <- computeModules(matrix,method = "Beckett")
modules <- module2constraints(matrix.bec)

df <- data.frame(c(rownames(matrix),colnames(matrix)),modules) 
colnames(df) <- c("vertices","modules")
list <- split(df$vertices,df$modules)

现在,对象list可以与igraph对象一起用作图形输入:

library(igraph)
graph <- graph_from_incidence_matrix(matrix,directed = F)

plot(graph,mark.groups = list)

这是让bipartiteigraph互相交谈的一种方式!

非常感谢您!