R - Merge 2 network with different color nodes
0
0
Entering edit mode
9.2 years ago

Hi,

I want to merge 2 networks but I want different color of their node. For example N1's vertices should be represented with color "Red" while of N2's with color "Green". So that I can identify which nodes in the merged network belongs to which network (N1 or N2).

I am using following code:

library(igraph)

dd <- read.table("g1.txt")
g1 <- graph.data.frame(dd) # N1
cd <- read.table("g2.txt")
g2 <- graph.data.frame(cd) #N2

n1 <- set.vertex.attribute(g1, "color", value=c("red"))
plot(n1) # Color of N1's nodes is Red

n2 <- set.vertex.attribute(g2, "color", value=c("green"))
plot(n2) # Color of N2's nodes is green

Problem arises when I merge them. The color of all nodes get same (I guess the by default node color)

g = graph.union(n1, n2, byname=TRUE) # Merging N1 and N2
plot(g) # Color of all nodes is same (by default=orange)

Please advise me how I can obtain different colors of nodes in merged network. Thanks.

merge R networks • 6.0k views
ADD COMMENT
2
Entering edit mode

It looks like the union method doesn't preserve the node attributes. In this case, a solution is to simply assign attributes after merging e.g. looping through all union nodes and assigning red or green based on whether they come from n1 or n2 (although there's likely a better way to do it).

Edit: A better way may be to use the option keep.x.vertex.attributes=TRUE as mentioned in the doc.

ADD REPLY
0
Entering edit mode
g = graph.union(n1, n2, byname=TRUE, keep.x.vertex.attributes=TRUE)

OR

g = graph.union(n1, n2, keep.x.vertex.attributes=TRUE)

Is not working for me...!

ADD REPLY
1
Entering edit mode

From ?graph.union:

'graph.union' keeps the attributes of all graphs. All graph,
vertex and edge attributes are copied to the result. If an
attribute is present in multiple graphs and would result a name
clash, then this attribute is renamed by adding suffixes: _1, _2, etc.

So I think the color attributes gets renamed color_1 and color_2. You should be able to just do:

V(g1)$color = "red"
V(g2)$color = "green"
g = graph.union(g1, g2, byname=TRUE)
V(g)$color_1 # lists "red" "red" "red" ...
V(g)$color_2 # lists "green" "reen" "green" ...
ADD REPLY

Login before adding your answer.

Traffic: 2312 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6