There are a few similar posts (like this one and this too), but my question might be more basic for the igraph
package functionality.
This is the minimal example that generates a simple graph:
library(MASS)
library(pcalg)
library(igraph)
# Some variance-covariance
Corrs <- matrix(c(1.0,0.6,0.7,0.5,0.6,1.0,0.5,0.6,0.7,0.5,1.0,0.7,0.5,0.6,0.7,1.0), 4, 4)
SDs <- c(1.0,0.5,2.0,1.0)
Covs <- SDs %*% t(SDs) * Corrs
dat = as.data.frame(mvrnorm(100, mu=c(0,0,0,0), Sigma=Covs))
n = nrow(dat)
V = colnames(dat) # node names
pc1 = pc(suffStat=list(C=cor(dat), n=n),
indepTest=gaussCItest, # indep.test: partial correlations
alpha=0.05, labels=V, u2pd='retry')
gr = graph_from_graphnel(pc1@graph)
plot.igraph(gr, layout=layout_in_circle,
vertex.label=V, vertex.shape='circle', vertex.size=30,
vertex.label.cex=0.55, vertex.label.color='black',
edge.arrow.size=0.6)
If I try to add an edge (for example, V2 —> V3) it ends with only that edge while others, "original" edges are gone:
gr = graph_from_graphnel(pc1@graph) + edge(2, 3, color='blue')
plot.igraph(gr, layout=layout_in_circle,
vertex.label=V, vertex.shape='circle', vertex.size=30,
vertex.label.cex=0.55, vertex.label.color='black',
edge.arrow.size=0.6)
I also tried with the add_edges()
function and got the same result.
So, how can I add an edge to the existing graph? And how can I mark that particular edge with different color
(which I managed) and lty
?
g <- gr |>
set_edge_attr("color", value = "green") |>
add_edges(c(2,3), color = "blue")
plot.igraph(g, layout=layout_in_circle,
vertex.label=V, vertex.shape='circle', vertex.size=30,
vertex.label.cex=0.55, vertex.label.color='black',
edge.arrow.size=0.6)
You need to set the colour attributes for all existing edges before adding another edge (with colour attribute). Otherwise, the colour will be NA, and the edge will not be drawn.
You can see from the following:
g <- gr |>
# set_edge_attr("color", value = "green") |>
add_edges(c(2,3), color = "blue")
E(g)[[]]
#+ 6/6 edges from 4b001d7 (vertex names):
# tail head tid hid weight color
#1 V1 V2 1 2 1 <NA>
#2 V1 V3 1 3 1 <NA>
#3 V2 V4 2 4 1 <NA>
#4 V3 V1 3 1 1 <NA>
#5 V3 V4 3 4 1 <NA>
#6 V2 V3 2 3 NA blue