【发布时间】:2021-08-30 03:54:55
【问题描述】:
以下代码生成一个网络图,可以将数据分成两组,但我想在上面应用 k-means,看看算法如何将数据聚类到同一组集群中。
library(igraphdata) # library for the graph data
data(karate)
V(karate) %>% print() # shows the list of the nodes
# Reproducible layout
set.seed(69)
l <- layout_with_kk(karate) #sets the layout.
# Plot undecorated Graph Network First.
igraph_options(vertex.size=10)
par(mfrow=c(1,1)) # sets plotting parameters
plot(karate, layout=l, vertex.label=V(karate),
vertex.color=NA) # Plots a basic Graph
# Now decorate, starting with labels.
V(karate)$label <- sub("Actor ", "", V(karate)$name)
V(karate)
# Two Club Leaders get shapes different from other club members.
V(karate)$shape <- "circle"
V(karate)[c("Hi", "John")]$shape <- "rectangle" # sets different shapes for these two only
# Differentiate two factions by color. (Similar to clustering & color-coded)
V(karate)[Faction == 1]$color <- "red"
V(karate)[Faction == 2]$color <- "dodgerblue"
# Vertex area proportional to vertex strength
# (i.e., total weight of incident edges).
V(karate)$size <- 4*sqrt(strength(karate))
V(karate)$size2 <- V(karate)$size * .5
# Weight edges by number of common activities
E(karate)$width <- E(karate)$weight
# Color edges by within/between faction.
F1 <- V(karate)[Faction==1] # sets variable for first cluster (faction)
F2 <- V(karate)[Faction==2] # similar to the above.
E(karate)[ F1 %--% F1 ]$color <- "pink"
E(karate)[ F2 %--% F2 ]$color <- "lightblue"
E(karate)[ F1 %--% F2 ]$color <- "green"
# Offset vertex labels for smaller points (size based, default is zero).
V(karate)$label.dist <-
ifelse(V(karate)$size >= 9.0, 0, 1.0)
# Plot decorated graph, using same layout.
plot(karate, layout=l)
最终输出:
【问题讨论】:
标签: r igraph k-means network-analysis