R:多路复用网络中的颜色属性

tcbh2hod  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(199)

我有以下定向社交网络的假数据框。from中的每个节点都属于特定的cluster(A,B,C,D,E)。

library(igraph)
library(ggplot2)
library(GGally)
library(tidyverse)
library(network)
library(sna)
library(intergraph)

# fake dataframe (on edges-level)
set.seed(2)
df <- data.frame(from = sample(LETTERS, size = 20, replace = TRUE),
                 to = sample(LETTERS, size = 20, replace = TRUE))

# cluster-definition on node-level (edited)
clusters <- data.frame(from = LETTERS) %>%
mutate(cluster = 1,
cluster = ifelse(from %in% c("A", "B", "C", "D"), 2, cluster),
cluster = ifelse(from %in% c("E", "F", "G", "H", "I", "J"), 3, cluster))

df2 <- df %>% filter(from != to)  # no self-loops

然后,我想绘制网络并根据它们所属的cluster为节点着色。

# Create graph
g <- graph_from_data_frame(df2, directed = TRUE)
V(g)$cluster <- df2$cluster

# plot network
ggnet2(simplify(g), node.color = V(g)$cluster) # doesn't work

我的问题是,当我使用set。seed(2)网络不是多路复用的,代码工作正常,但如果我使用set。seed(3)例如,V(g)$cluster <- df2$cluster会产生问题:

Error in i_set_vertex_attr(x, attr(value, "name"), index = value, value = attr(value,  : 
  Length of new attribute value must be 1 or 21, the number of target vertices, not 18

我认为这是因为simplify(g)减少了节点的数量,使得节点的数量小于df2$cluster的长度。
当然,我可以使用sed。seed(2),但我的真实的网络似乎是多路复用的。
不幸的是,我不知道,我怎么能解决这个问题。有人能帮忙吗

h5qlskok

h5qlskok1#

至少在这个模拟过程中,您似乎是按边而不是按节点设置集群。这样有用吗

library(igraph)

gen_net <- function(nedges) {
    df <- data.frame(
        from = sample(LETTERS, size = nedges, replace = TRUE),
        to = sample(LETTERS, size = nedges, replace = TRUE)
    )

    df2 <- df[which(df$from != df$to), ]
    
    nodes <- unique(unlist(df2))
    nnodes <- length(nodes)
    clusters <- sample(LETTERS[1:5], nnodes, replace = TRUE)

    g <- graph_from_data_frame(df2, directed = TRUE)
    V(g)$cluster <- clusters
    V(g)$color <- sapply(V(g)$cluster, function(i) grep(i, LETTERS))

    return(g)
}

set.seed(2)
g <- gen_net(20)
plot(g)

set.seed(3)
g <- gen_net(20)
plot(g)

编辑

如果你已经有了社区成员资格,你应该仍然很好。下面我做了一个随机图,但我找到了具有cluster_walktrap()的社区,并将其视为给定的。在图中,社区成员由节点颜色显示,并且多边用较粗、较暗的线强调。

library(igraph)
set.seed(1)

N <- 100
m <- 2
p <- .1

g <- sample_pa(N, m = m, start.graph = make_star(3))
h <- sample_pa(N, m = m, start.graph = make_star(3))

G <- disjoint_union(g, h)

rewire <- function(G) {
    nodes <- as.numeric(V(G))
    edges <- ends(G, es = E(G))
    rns <- runif(nrow(edges))
    newtails <- ifelse(rns < p, sample(nodes, 1), edges[, 2])
    graph_from_edgelist(cbind(edges[, 1], newtails))
}

S <- rewire(G) # this graph has multi-edges in it

clusters <- cluster_walktrap(S)
V(S)$color <- membership(clusters)
E(S)$color <- ifelse(which_multiple(S), "black", "gray60")
E(S)$width <- ifelse(which_multiple(S), 2, 1)
dev.new(height = 10, width = 10)
plot(S, vertex.label = "", vertex.size = 3, edge.arrow.size = 0.5)

相关问题