R iGraph - 如何为最小生成树中使用的边着色

问题描述

我想通过对解决方案中使用的边着色来绘制最小生成树 (MST) 的解决方案。

library("igraph")
A = matrix(c(0,23,11,5,26,22,9,13,30,18,7,29,15,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))

enter image description here

如果我使用 mst() 包,我得到以下解决方

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

我想绘制 g 并为上面提供的解决方案中使用的边缘着色。例如,我可以使用以下代码,但是,它只打印使用的边缘。我想打印所有边缘,同时区分 MST 中使用的边缘。

plot(mst(g),layout=layout.reingold.tilford,edge.label=E(mst(g))$weight)

enter image description here

我尝试了 E(g)$color <- ifelse(E(g) %in% mst(g),"black","red") 但它不能正常工作。

解决方法

你可以试试下面的代码

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
  )

给出

enter image description here