【问题标题】:R iGraph - how to color edges used in minimum spanning treeR iGraph - 如何为最小生成树中使用的边缘着色
【发布时间】:2021-10-05 08:08:01
【问题描述】:

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

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))

如果我使用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)

我试过E(g)$color &lt;- ifelse(E(g) %in% mst(g), "black", "red"),但它不能正常工作。

【问题讨论】:

    标签: r if-statement colors igraph minimum-spanning-tree


    【解决方案1】:

    你可以试试下面的代码

    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
      )
    

    给了

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2016-11-29
      • 2018-11-04
      • 1970-01-01
      • 2019-05-08
      相关资源
      最近更新 更多