gpt4 book ai didi

r - 如何展开使用 R 中的 igraph 包制作的社区图

转载 作者:行者123 更新时间:2023-12-02 03:09:08 25 4
gpt4 key购买 nike

尝试在推文数据中查找社区。不同单词之间的余弦相似度形成邻接矩阵。然后,我根据该邻接矩阵创建了图。图表的可视化是这里的任务:

# Document Term Matrix
dtm = DocumentTermMatrix(tweets)

### adjust threshold here
dtms = removeSparseTerms(dtm, 0.998)
dim(dtms)

# cosine similarity matrix
t = as.matrix(dtms)

# comparing two word feature vectors
#cosine(t[,"yesterday"], t[,"yet"])

numWords = dim(t)[2]

# cosine measure between all column vectors of a matrix.
adjMat = cosine(t)

r = 3
for(i in 1:numWords)
{
highElement = sort(adjMat[i,], partial=numWords-r)[numWords-r]
adjMat[i,][adjMat[i,] < highElement] = 0
}

# build graph from the adjacency matrix
g = graph.adjacency(adjMat, weighted=TRUE, mode="undirected", diag=FALSE)
V(g)$name

# remove loop and multiple edges
g = simplify(g)
wt = walktrap.community(g, steps=5) # default steps=2
table(membership(wt))

# set vertex color & size
nodecolor = rainbow(length(table(membership(wt))))[as.vector(membership(wt))]
nodesize = as.matrix(round((log2(10*membership(wt)))))
nodelayout = layout.fruchterman.reingold(g,niter=1000,area=vcount(g)^1.1,repulserad=vcount(g)^10.0, weights=NULL)

par(mai=c(0,0,1,0))
plot(g,
layout=nodelayout,
vertex.size = nodesize,
vertex.label=NA,
vertex.color = nodecolor,
edge.arrow.size=0.2,
edge.color="grey",
edge.width=1)

我只是想在不同的集群/社区之间有更多的差距。

different communities are shown by different colors

最佳答案

据我所知,仅使用 igraph 无法将同一社区的顶点布局得彼此靠近。我已经在我的包NetPathMiner中实现了这个功能。仅仅为了可视化功能安装这个包似乎有点困难。我将在这里编写它的简单版本并解释它的作用。

layout.by.attr <- function(graph, wc, cluster.strength=1,layout=layout.auto) {  
g <- graph.edgelist(get.edgelist(graph)) # create a lightweight copy of graph w/o the attributes.
E(g)$weight <- 1

attr <- cbind(id=1:vcount(g), val=wc)
g <- g + vertices(unique(attr[,2])) + igraph::edges(unlist(t(attr)), weight=cluster.strength)

l <- layout(g, weights=E(g)$weight)[1:vcount(graph),]
return(l)
}

基本上,该函数添加一个额外的顶点,该顶点连接到属于同一社区的所有顶点。布局是根据新图表计算的。由于每个社区现在都通过一个公共(public)顶点连接,因此它们倾向于聚集在一起。

正如 Gabor 在评论中所说,增加边权重也会产生类似的效果。该函数通过增加cluster.strength来利用此信息,为创建的顶点及其社区之间的边赋予更高的权重。

如果这还不够,您可以通过在同一社区的所有顶点之间添加边(形成一个派系)来扩展此原则(计算连接更紧密的图上的布局)。根据我的经验,这有点矫枉过正。

关于r - 如何展开使用 R 中的 igraph 包制作的社区图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28715736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com