改变igraph图中子图的颜色

时间:2012-09-28 20:18:58

标签: r igraph

我有以下代码来绘制图形的最小生成树

## g is an igraph graph
mst = minimum.spanning.tree(g)
E(g)$color <- "SkyBlue2"

## how to I make mst a different color
E(g)[E(mst)]$color = "red"  ### <---- I WANT TO DO ESSENTIALLY THIS

plot(g,  edge.label=E(g)$weight)

也就是说,对于一个简单的图表,我找到了mst。我想将mst更改为红色并将mst绘制为主图的一部分。为此,我想选择同样位于g的{​​{1}}边缘。我该怎么做?


更新:

更一般地说,我有一个图mst,它是g0的mst,有g个顶点。它的构建如下

n

我知道我可能没有使用igraph的许多有用功能,但我确实在此循环结束时让## implementing the Dijkstra-Prim algorithm v0 = sample(1:n, 1) g0 = graph.empty(n=n, directed=FALSE) weight.g0 = 0 while(length(setdiff(1:n, v0) > 0)) { ## chose the shortest edge in the cut set of g ## to find the cut, figure out the set of edges where vertex is ## in v0 and the other is not cutset = E(g)[ v0 %->% setdiff(1:n, v0)] ## find the lightest weight edge cutweights = E(g)$weight[cutset] lightest_edge_idx = which(cutweights == min(cutweights))[1] weight.g0 = weight.g0 + min(cutweights) ## get the vertices of the lightest weight edge, add to path lightest_edge = cutset[as.numeric(cutset)[lightest_edge_idx]] vertices = get.edges(g, as.numeric(lightest_edge)) g0 <- add.edges(g0, vertices, weight=min(cutweights)) ## now that we have the vertices, add the one that is not in the ## graph already for(vtx in vertices) { if(!(vtx %in% v0)) { v0 = c(vtx, v0) } } } 成为mst。鉴于此,我有

g0

我的问题是,如何为E(g)中同样位于E(g0)的边缘分配属性?

1 个答案:

答案 0 :(得分:5)

这实际上非常简单,因为minimum.spanning.tree()保留了边缘属性。因此,您只需要指定一个边缘ID属性,然后您将看到哪些边缘颜色为红色。它是这样的:

# Some test data, no edge weights, quite boring
g <- erdos.renyi.game(20,2/20)
g
# IGRAPH U--- 20 24 -- Erdos renyi (gnp) graph
# + attr: name (g/c), type (g/c), loops (g/l), p (g/n)

E(g)$id <- seq_len(ecount(g))
mst <- minimum.spanning.tree(g)
mst
# IGRAPH U--- 20 18 -- Erdos renyi (gnp) graph
# + attr: name (g/c), type (g/c), loops (g/l), p (g/n), id (e/n)
E(mst)$id
# [1]  1  2  3  6  7  8  9 10 11 12 13 16 18 19 20 22 23 24

E(g)$color <- "black"
E(g)$color[E(mst)$id] <- "red"
plot(g)

enter image description here

相关问题