Reputation: 651
I would like to plot the solution of the minimum spanning tree(MST) by coloring the edges used in the solution.
library("igraph")
A = matrix(c(0, 23, 11, 5, 26, 22,23, 0, 9, 13, 30, 18,11, 9, 0, 9, 7, 29,5, 13, 9, 0, 15, 5,26, 30, 7, 15, 0, 9,22, 18, 29, 5, 9, 0),
nrow= 6 , ncol= 6 ,byrow = TRUE)
g <- graph.adjacency(A,weighted=TRUE, mode = c("undirected"))
plot(g,edge.label=round(E(g)$weight, 3))
If I use mst()
package, I get the following solution
mst(g)
IGRAPH ac800ea U-W- 6 5 --
+ attr: weight (e/n)
+ edges from ac800ea:
[1] 1--4 2--3 3--5 4--6 5--6
I would like to plot g
and color the edges used in the solution provided above. For instance, I can use the following code, however, it only prints the edges used. I would like to print all edges while distinguishing the edges used in the MST.
plot(mst(g),layout=layout.reingold.tilford,edge.label=E(mst(g))$weight)
I tried E(g)$color <- ifelse(E(g) %in% mst(g), "black", "red")
however it did not work properly.
Upvotes: 1
Views: 363
Reputation: 102241
You can try the code below
left_join(
get.data.frame(g),
cbind(get.data.frame(mst(g)), color = "black")
) %>%
mutate(color = replace_na(color, "red")) %>%
graph_from_data_frame(directed = FALSE) %>%
plot(
edge.label = E(.)$weight,
edge.color = E(.)$color
)
which gives
Upvotes: 1