The goal of this tutorial is to show an example of network visualizations using geomnet. I am going to use the Florentine marriage data which is a part of the sna package.
As always, we start by loading the necessary libraries:
library(network)
library(ggplot2)
library(scales)
library(devtools)
library(geomnet)
library(RColorBrewer)
library(sna)
library(ergm)
library(ggrepel)
Open the data:
data(florentine)
The most tedious step is to prepare the data. For this example, I will use gplot to get the coordinates for node positions. This is helpful if you want to fix the layout of the nodes and plot the network multiple times.
set.seed(38)
positions <- gplot(flomarriage)
For the actual graph, I am going to use geom_net, which requires the data in a specific format. To put the data in this format, you need to extract the list of edges (just the pairs of nodes that are connected by an edge), and the full list of nodes (even if a node is a singleton and will not appear in the list of edges).
d <- as.matrix(flomarriage,matrix.type="edgelist") #This gives me a list of edges
colnames(d)<-c("id1","id2") # I name them for my convenience.
#Get a list of vertices:
mynodes<-attr(d,"vnames")
mynodes1<-as.data.frame(cbind(names1=mynodes, id=seq(1:length(mynodes)))) #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.
mynodes<-as.data.frame(cbind(names=mynodes, id=seq(1:length(mynodes)),positions)) #I also want to add position coordinates.
#Add names to edgelist:
mynet<-merge(d,mynodes1, by.x="id1", by.y="id")
mynodes2<-mynodes1
colnames(mynodes2)<-c("names2","id")
mynet<-merge(mynet,mynodes2, by.x="id2", by.y="id")
mynet<-mynet[,c(3,4,2,1)]
#Combine edges and nodes into an object suitable for geomnet:
mynet1<-fortify(as.edgedf(mynet), mynodes) #You need to provide a list of edges and a list of nodes.
Now we can finally make the plot.
#Specify theme:
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:
p <- ggplot(data = mynet1)+ geom_net(aes(from_id =from_id, to_id = to_id,x = x, y = y),labelon=TRUE,repel=TRUE,layout.alg=NULL,ecolour="red3")+ylab("")+xlab("") +
scale_x_discrete(expand=c(0.2,0,0.2,0))
p