1 Introduction

This tutorial introduces network analysis using R. In this session you will learn how to create and modify network graphs. The entire code for the sections below can be downloaded here.

How can you display the relatioship between different elements, be they authors, characters, or words?

The most common way to visualize such relatioships are networks. Networks, also called graphs, consist of nodes (typically represented as dots) and edges (typically represented as lines) and they can be directed or undirected networks.

In directed networks, the direction of edges is captured. For instance, the exports of countries. In such cases the lines are directed and typically have arrows to indicate direction. The thinkness of lines can also be ustilized to encode information such as frequency of contact.

Networks can have different layouts.

The centrality of networks is measured as

  • Node degree

  • Node closeness (the closer two nodes are, the closer connected ethy are)

  • Node betweeness

  • Edge betweenness

There are two ways to capture the basic structure of a network:

  • Adjacency matrix (Matrix of 0s and 1s depending on whether the nodes are connected or not)
##   A B C D E F G
## A 0 1 1 1 1 1 0
## B 1 0 0 0 0 0 0
## C 1 0 0 0 0 0 0
## D 1 0 0 0 0 0 0
## E 1 0 0 0 0 1 0
## F 1 0 0 0 1 0 1
## G 0 0 0 0 0 1 0
  • Edge list (Two column matrix to indicate which nodes are connected)
##   V1 V2
## 1  A  B
## 2  A  C
## 3  A  D
## 4  A  E
## 5  A  F
## 6  E  F
## 7  F  G

The example that we will be concerned with focuses on the first type of data as it is by far the most common way in which relationships are coded.To show how to cerate a netwrok, we will have a look at the network that the characters in William Shakespeare’s Romeo and Juliet form.

Preparation and session set up

As all calculations and visualizations in this tutorial rely on “R”, it is necessary to install “R” and “RStudio”. If these programs (or, in the case of “R”, environments) are not already installed on your machine, please search for them in your favorite search engine and add the term “download”. Open any of the first few links and follow the installation instructions (they are easy to follow, do not require any specifications, and are pretty much self-explanatory).

In addition, certain “libraries” or “packages” need to be installed so that the scripts shown below are executed without errors. Before turning to the code below, please install the libraries by running the code below this paragraph. If you have already installed the libraries mentioned below, then you can skip ahead ignore this section. To install the necessary libraries, simply run the following code - it may take some time (between 1 and 5 minutes to install all of the libraries so you do not need to worry if it takes some time).

# clean current workspace
rm(list=ls(all=T))
# set options
options(stringsAsFactors = F)         # no automatic data transformation
options("scipen" = 100, "digits" = 4) # supress math annotation
# install libraries
install.packages(c("GGally", "network", "sna", "ggplot2"))

Once you have installed “R” and “R-Studio”, and have also initiated the session by executing the code shown above, you are good to go.

2 Creating a network of characters in Romeo and Juliet

In a first step, we load the necessary packages from the library.

library(GGally)
library(network)
library(sna)
library(ggplot2)

Next, we load the data. The data we will use to show how to perform a network analysis are characters from Shakespeare’s “Romeo and Juliet”. The data we load consists of a matrix that shows how often different characters have co-occurred together in a scene. This matrix can be loaded by using the read.table command.

romeo <- read.delim("https://SLCLADAL.github.io/data/romeo.txt", header = TRUE)
# show first 5 rows and first 5 columns of the data
romeo[1:5, 1:5]
##             Abraham Benvolio LordCapulet Gregory LadyCapulet
## Abraham           1        1           1       1           1
## Benvolio          1        7           3       1           2
## LordCapulet       1        3           9       1           7
## Gregory           1        1           1       1           1
## LadyCapulet       1        2           7       1          10

The data shows how often a character has appeared with each other character in the play - only Friar Lawrence and Friar John were excluded because they only appear in one scene where they talk to each other.

In a next step, we create a network object from the matrix. In addition, we define vertex names as these will be used as labels in the network plot.

net = network(romeo,
              directed = FALSE,
              ignore.eval = FALSE,
              names.eval = "weights"
)
# vertex names
network.vertex.names(net) = rownames(romeo)
net
##  Network attributes:
##   vertices = 23 
##   directed = FALSE 
##   hyper = FALSE 
##   loops = FALSE 
##   multiple = FALSE 
##   bipartite = FALSE 
##   total edges= 143 
##     missing edges= 0 
##     non-missing edges= 143 
## 
##  Vertex attribute names: 
##     vertex.names 
## 
##  Edge attribute names: 
##     weights

Unfortunately, network object are somewhat obscure in that they can not be displayed as simple data frames.

2.1 Creating basic networks

However, this does not matter at this point and we continue by visualizing the network in a simple network plot using the ggnet2 function.

ggnet2(net, 
       size = 6, 
       color = "goldenrod", 
       edge.size = .5,
       edge.color = "lightgrey", 
       label = TRUE, 
       label.size = 3)

The basic network shown above only shows who has co-occurred with whom but it is not really informative. Therefore, we add information to the network object.

2.2 Modifying networks

To add information to a simple network graph, we cerate a new variable. This variable shows to which family each of the characters belong. To do this, we create a separate vector for each family which holds the characters that are members of this family. Then, we create a variable in the network object called “Family” which represents the family which the characters belong to.

# create vectors with names of characters
escalus <- c("PrinceEscalus", "CountParis", "Mercutio", "PageToParis")
capulet <- c("LordCapulet", "LadyCapulet", "Juliet", "Tybalt", "Nurse",
             "Peter", "Gregory", "Sampson", "Anthony", "Potpan", "Servant",
             "CapuletServant", "OldCapulet")
montague <- c("LordMontague", "LadyMontague", "Romeo", "Benvolio",
              "Balthasar", "Abraham")
# add color by group
net %v% "Family" = ifelse(network.vertex.names(net) %in% capulet, "Capulet", 
                   ifelse(network.vertex.names(net) %in% montague, "Montague", 
                   ifelse(network.vertex.names(net) %in% escalus, "Escalus", "other")))

We can now use the family variable to define a color so that each character can be associated with his or her family by coloring. In addition, we specify the edge attributes so that the thickness and the type of a line represent how often characters have co-occurred. Characters that co-occur frequently are connected by thick, straight, solid lines whereas characters that co-occurred together only infrequently are connected by thin, dotted lines.

# modify color
net %v% "color" = ifelse(net %v% "Family" == "Capulet", "goldenrod", 
                  ifelse(net %v% "Family" == "Montague", "indianred4", 
                  ifelse(net %v% "Family" == "Escalus", "burlywood", "gray60")))
# rescale edge size
set.edge.attribute(net, "weights", ifelse(net %e% "weights" <= 1, 0.25, 
                                   ifelse(net %e% "weights" <= 3, .5, 1)))
# define line type
set.edge.attribute(net, "lty", ifelse(net %e% "weights" == 0.25, 3, 
                                      ifelse(net %e% "weights" == .5, 2, 1)))

We now visualize the network again but include information such as who belongs to which family (the translucent circles around the names) and how often they have co-occurred (thickness any type of the lines). We also specify alpha values which make lines and circles more or less translucent (the higher the value, the more translucent are the lines and circles).

ggnet2(net, 
       color = "color", 
       label = TRUE, 
       label.size = 3,
       alpha = 0.2,
       size = "degree",
       size.cut = 3,
       edge.size = "weights",
       edge.lty = "lty",
       edge.alpha = 0.5) +
  guides(color = FALSE, size = FALSE)

We have now plotted the network of characters in Shakespeare’s Romeo and Juliet and we have added additional information to this plot. The characters are shown by name and the color behind their name informs us about which family they belong to (Capulet = golden, Montague = red, Escalus = burlywood, other = gray). The linetype and line thickness both provide information on how frequently characters interacted: slim dotted gray lines indicate that the characters only co-occurred once, dashed gray lines indicate that the characters co-occured up to three times and thick solid gray lines show that the characters co-occured more than 3 times together.

3 Creating two-layer networks

We will now create a different network - a network that links two types of entities, e.g. people to events or words to documents. In this example, we will link authors to journals. In contrast to the previous example, where we loaded already existing data, we create the data ourselves this time.

In a first step, we create a data frame representing three journals (JPrag, ELL, and WE) and four authors (MS, MH, NM, LM) who have have published in these journals.

# weighted adjacency matrix
authorjournal = data.frame(JPrag = c(1, 5, 1, 3),
                 Language = c(0, 0, 3, 1),
                 Lingua = c(1, 0, 1, 0),
                 row.names = c("Martin", "Michael", "Felicity", "Ilana"))
authorjournal
##          JPrag Language Lingua
## Martin       1        0      1
## Michael      5        0      0
## Felicity     1        3      1
## Ilana        3        1      0

Next, we create a network out of the data frame.

# create network
ajn = network(authorjournal,
              matrix.type = "bipartite",
              ignore.eval = FALSE,
              names.eval = "weights")

Now that we have created a network object, we can visualize it. We will use colors and shapes to differentiate between authors and jorunals (or events).

# set colors for each mode
clrs = c("actor" = "red", "event" = "blue")
ggnet2(ajn, 
       color = "mode", 
       shape = "mode",
       size = 5,
       alpha = 0.7,
       palette = clrs,
       label.size = 3,
       label.color = "white",
       label = TRUE, 
       edge.size = "weights",
       edge.alpha = 0.3) +
  theme(panel.background = element_rect(fill = "grey15"))

The colors and shapes indicate the type of element: red circles indicate authors while blue triangles indicate journals. The thickness of the lines indicate that and how often an author has published in one of the journals. As such the lines indicate journal preference and can serve as a proxy for scientific field. In our example, Michael has very strong ties to JPrag while Felicity has stronger ties to Language. This could be interpreted to indicate that Michael is more interested in pragmatics while Felicity is more intersted in General Linguistics. Ilana has ties to both JPrag and Language but the thickness of the lines suggest that she too is more intersted in Pragmatocs while also dealing with General Linguistics.

Finally, you can nspect the data (which makes it easier to change, adapt, and modify) in the following way..

ggnet2(ajn, 
       color = "mode", 
       shape = "mode",
       size = 5,
       alpha = 0.7,
       palette = clrs,
       label.size = 3,
       label.color = "white",
       label = TRUE, 
       edge.size = "weights",
       edge.alpha = 0.3)$data
##      label alpha color shape size          x          y
## 1   Martin   0.7 actor actor    5 0.72027789 0.07123702
## 2  Michael   0.7 actor actor    5 0.00000000 0.00000000
## 3 Felicity   0.7 actor actor    5 0.65763889 0.65978584
## 4    Ilana   0.7 actor actor    5 0.06751894 0.71713124
## 5    JPrag   0.7 event event    5 0.32019425 0.31980820
## 6 Language   0.7 event event    5 0.37777052 1.00000000
## 7   Lingua   0.7 event event    5 1.00000000 0.38282693

We have reached the end of this tuorial and you now know how to create and modify networks in R and how you can highlight aspects of your data.

How to cite this tutorial

Schweinberger, Martin. 2020. Network Analysis using R. Brisbane: The University of Queensland. url: https://slcladal.github.io/basicnetwork.html.