Plotting Networks in R

Using the network package, you can plot graphs in a flexible and powerful way.  Often, when plotting a network, we want to vary the color, size, or shape of the vertices based on some attributes.  Let's say that we have a freewheeling sexual network (easier to simulate) and we would like to color the vertices of the graph according to their HIV sero-status.  Let's also say that we want to make the shape of each vertex reflect the sex of the individual.  We use the following code:

# begin with randomly constructed edgelist

n1 <- round(1+10*runif(50)) n2 <- round(1+10*runif(50)) eee <- cbind(n1,n2)[order(n1),] net <- network(eee,directed=FALSE) # this will be a dense network! hiv <- rbinom(50,size=1,prob=0.2) # random infections! sex <- rbinom(50,size=1,prob=0.5) # random sexes! set.vertex.attribute(net,"hiv",hiv+1) set.vertex.attribute(net,"sex",sex+3) ## now plot plot(net, vertex.col="hiv", vertex.sides="sex", vertex.cex=5, vertex.rot=-30, edge.lwd=1) [/r] I definitely wouldn't want to be part of that party.

One thought on “Plotting Networks in R”

Leave a Reply

Your email address will not be published. Required fields are marked *