如何解决如何使用其他输入在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
是否可以使用bipartite
中igraph
的输出,以便在社区周围自动绘制多边形?
我研究了文档,在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)
这是让bipartite
和igraph
互相交谈的一种方式!
非常感谢您!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。