Load Libraries:
library(network)
library(ggplot2)
library(scales)
library(devtools)
library(geomnet)
library(RColorBrewer)
library(sna)
library(ergm)
Florentine marriages example:
rm(list = ls())
#Make data accessible
data(florentine)
Generate fixed vertex positions:
set.seed(12063)
positions<-gplot(flomarriage)
Get a list of edges:
myedges<-as.edgelist(flomarriage,output="matrix", directed=TRUE) #This gives me a list of edges
colnames(myedges)<-c("id1","id2") # I name them for my convenience.
Get a list of vertices:
mynodes<-attr(myedges,"vnames")
mynodes<-as.data.frame(cbind(names=mynodes, id=as.factor(seq(1:length(mynodes))),positions)) #Notice that the list of edges does not have names in it, just the numeric identifies, so I want to have a list of both numerical identifiers and names.
I really want my edges named rather than use numeric identifiers:
myedges<-merge(myedges,mynodes,by.x="id1",by.y="id")
myedges<-merge(myedges,mynodes,by.x="id2",by.y="id")
myedges<-myedges[,c(3,6)]
Combine edges and nodes into an object suitable for geomnet:
mynet<-fortify(as.edgedf(as.data.frame(myedges)), as.data.frame(mynodes)) #You need to provide a list of edges and a list of nodes.
## Using names.x as the from node column and names.y as the to node column.
## If this is not correct, rewrite dat so that the first 2 columns are from and to node, respectively.
## Joining edge and node information by from_id and names respectively.
Set the theme and make the graph
theme_set(theme_grey() + theme(legend.position="none",
panel.background = element_rect(fill = NA, color = 'black'),
axis.ticks = element_blank(), axis.text = element_blank()))
#Make a graph:
p1 <- ggplot(data = mynet)+ geom_net(aes(from_id =from_id, to_id = to_id,x=as.numeric(as.character(x)),y=as.numeric(as.character(y))),repel=TRUE,color="red", layout.alg=NULL,labelon=TRUE)+ylab("")+xlab("") +
scale_x_discrete(expand=c(0.2,0,0.2,0))+ggtitle("Florentine Marriages")
p1
Suggested exercise: Make an anlogous graph using the flobusiness data.