Reputation: 361
I have an undirected network of 300 nodes built based on a binary adjacency matrix. 50 nodes are labeled as minority
and the rest as majority
. I want to set edge colors (and attributes) based on the nodes they connect: within.mino
, within.majo
, and between.minomajo
.
I have seen ways of coloring edges based on one of the nodes like this but this is not my problem. I also have tried this solution but couldn't adapt it to my problem.
Here is a minimal reproducible example:
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)
I want to assign the following labels on the edges, based on to which type of node they're connected to:
Upvotes: 1
Views: 362
Reputation: 6768
You can use the %--%
selector to find edges that meet your conditions and the set their color
. Try out:
# 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)
Instead of color
, you can also use the label
if you want:
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)
Upvotes: 1