根据节点标签为边缘着色(连接相似和异种的边缘颜色不同)

时间:2019-06-28 08:29:15

标签: r igraph network-analysis

我有一个基于二进制邻接矩阵的300个节点的无向​​网络。 50个节点标记为minority,其余节点标记为majority。我想根据它们连接的节点设置边缘颜色(和属性):within.minowithin.majobetween.minomajo

我已经看到了基于像this这样的节点之一为边缘着色的方法,但这不是我的问题。我也尝试过this solution,但无法使其适应我的问题。

这是一个最小的可重现示例:

library(igraph)

# making the binary matrix
set.seed(10)
m.non_sym <- matrix(sample(0:1, 7, replace=TRUE), 10, 10)

# making it symmetrical
m.lower <- lower.tri(m.non_sym)*m.non_sym
m <- m.lower + t(m.lower)
diag(m) <- 0

# making the graph
g <- m %>% graph_from_adjacency_matrix(mode="undirected")

# assigning labels
V(g)$partition <- c(rep("minority", 4),
                    rep("majority", 6))

# plotting the graph
g %>% plot(vertex.size=10,
           vertex.color=c("skyblue", "pink")[1+(V(g)$partition=="majority")],
           edge.width = 3)

我想根据边缘连接到的节点类型为边缘分配以下标签:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用%--%选择器来找到满足您条件的边并设置其color。试试:

# select edges and set color 
E(g)[V(g)[partition == "minority"] %--% V(g)[partition == "minority"]]$color <- "blue" # within.mino
E(g)[V(g)[partition == "minority"] %--% V(g)[partition == "majority"]]$color <- "red" # between.minomajo
E(g)[V(g)[partition == "majority"] %--% V(g)[partition == "majority"]]$color <- "yellow" # within.majo
# plot
g %>% plot(vertex.size = 10,
           vertex.color = c("skyblue", "pink")[1 + (V(g)$partition == "majority")],
           edge.width = 3)

enter image description here

如果需要,也可以使用color代替label

E(g)[V(g)[partition == "minority"] %--% V(g)[partition == "minority"]]$label <- "within.mino"
E(g)[V(g)[partition == "minority"] %--% V(g)[partition == "majority"]]$label <- "between.minomajo"
E(g)[V(g)[partition == "majority"] %--% V(g)[partition == "majority"]]$label <- "within.majo"

g %>% plot(vertex.size = 10,
           vertex.color = c("skyblue", "pink")[1 + (V(g)$partition == "majority")],
           edge.width = 3)

enter image description here

相关问题