簡體   English   中英

如何在R中展開使用igraph包制作的社區圖

[英]How to spread out community graph made by using igraph package in R

試圖在推特數據中找到社區。 不同單詞之間的余弦相似性形成鄰接矩陣。 然后,我從該鄰接矩陣中創建了圖形。 圖形的可視化是這里的任務:

# 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)

我只想在不同的集群/社區之間留下更多的差距。

不同的社區以不同的顏色顯示

據我所知,您不能僅使用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)
}

基本上,該函數添加了一個額外的頂點,該頂點連接到屬於同一社區的所有頂點。 布局基於新圖計算。 由於每個社區現在都由一個共同的頂點連接,因此它們傾向於聚集在一起。

正如Gabor在評論中所說,增加邊緣權重也會產生類似的效果。 該函數利用此信息,通過增加cluster.strength ,創建的頂點與其社區之間的邊緣被賦予更高的權重。

如果這仍然不夠,則通過在相同社區的所有頂點之間添加邊(形成一個集團)來擴展此原則(在更連接的圖上計算布局)。 根據我的經驗,這有點矯枉過正。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM