Curious56
Curious56

Reputation: 51

Network plotting with igraph in R - differntiating vertices and edges

I'm struggling with some social network mapping with R using igraph. I would like to produce a plot showing the relationships of local representative (e.g. Bill) with individuals and administrative bodies in their area. I've been able to plot vertices for Bill and his contacts with edges using the following in a graph.data.frame:

who contact     weight  associate
Bill    district    1   y
Bill    region      2   n
Bill    village A   1   y
Bill    village B   2   n
Bill    social worker   1   n
Bill    steve       1   y
Bill    church      2   n
Bill    jane        1   y
Bill    village A Admin 1   n
Bill    village B Admin 1   n

I would like to differentiate the vertices by color as to whether or not they are one of Bill's associates. I tried

V(g)$color <- ifelse(V(g) 

but get either an error message or nothing changes. I would also like to differentiate the edges in different colors by weight to represent between Bill's direct or indirect contacts using the weight variable.

Any guidance on how I can enhance Bill's plot or whether I should be using a different dataframe would be greatly appreciated.

Upvotes: 0

Views: 1059

Answers (1)

MrFlick
MrFlick

Reputation: 206576

The reason why your "associate" code isn't working is that when you do graph.data.frame the extra attributes are stored with the edges you supply, not the vertices. Here's how you can add the vertex information (And plot the weights using @jlhoward's suggestion)

#sample data    
dd <- structure(list(who = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L), .Label = "Bill", class = "factor"), contact = c("district", 
"region", "villageA", "villageB", "socialworker", "steve", "church", 
"jane", "villageAAdmin", "villageBAdmin"), weight = c(1L, 2L, 
1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), associate = c("y", "n", "y", 
"n", "n", "y", "n", "y", "n", "n")), .Names = c("who", "contact", 
"weight", "associate"), row.names = c(NA, -10L), class = "data.frame")

and now the code

library(igraph)
gg <- graph.data.frame(dd[,1:3])

V(gg)[dd$contact]$associate <- dd$associate
V(gg)$color <- ifelse(V(gg)$associate=="y", "green","orange")

plot(gg,edge.color=E(gg)$weight)

which produces

output

Upvotes: 1

Related Questions