Introduction

This tutorial introduces network analysis using R. Network analysis is a method for visualization that can be used to represent various types of data. In addition to being a visualization technique, networks have certain statistical properties that can be compared which makes network analysis a very useful procedure. To this end, this tutorial shows how to create and modify network graphs. The entire R-markdown document for the sections below can be downloaded here.

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

The most common way to visualize such relationships are networks (Silge and Robinson 2017 : 131-137). 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 create a network, we will have a look at the network that the characters in William Shakespeare’s Romeo and Juliet form.

Preparation and session set up

This tutorial is based on R. If you have not installed R or are new to it, you will find an introduction to and more information how to use R here. For this tutorials, we need to install certain packages from an R library so that the scripts shown below are executed without errors. Before turning to the code below, please install the packages by running the code below this paragraph. If you have already installed the packages mentioned below, then you can skip ahead ignore this section. To install the necessary packages, 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", "tidyverse", "knitr", 
                   "kableExtra", "gutenbergr", "tm", "Matrix"))

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

1 A network of Romeo and Juliet

This section shows hw to create a network that shows which characters in William Shakespeare’s Romeo and Juliet co-occurred in the play and how often they co-occurred. In a first step, we load the necessary packages from the library.

# activate packages
library(GGally)
library(network)
library(tidyverse)
library(sna)
library(knitr)
library(kableExtra)
library(gutenbergr)
library(tm)
library(Matrix)
library(tibble)

The issue we want to investigate here relates to networks of personas in Shakespeare’s Romeo and Juliet and we thus load this famous work of fiction. Now that we have loaded the data, we need to split the data into scenes. Scenes during which personas leave or enter will have to be split too so that we arrive at a table that contains the personas that are present during a sub-scene.

# load data
romeo <- read.delim("https://slcladal.github.io/data/romeo.txt", sep = "\t")
# inspect data
romeo
##                Abraham Benvolio LordCapulet Gregory LadyCapulet LadyMontague
## Abraham              1        1           1       1           1            1
## Benvolio             1        7           3       1           2            1
## LordCapulet          1        3           9       1           7            1
## Gregory              1        1           1       1           1            1
## LadyCapulet          1        2           7       1          10            1
## LadyMontague         1        1           1       1           1            1
## LordMontague         1        2           2       1           3            1
## PrinceEscalus        1        2           2       1           3            1
## Romeo                1        7           5       1           4            1
## Sampson              1        1           1       1           1            1
## Tybalt               1        3           2       1           2            1
## CountParis           0        1           4       0           3            0
## CapuletServant       0        2           2       0           1            0
## Juliet               0        1           4       0           5            0
## Nurse                0        2           5       0           5            0
## Mercutio             0        4           0       0           1            0
## Chorus               0        1           1       0           0            0
## Friar                0        0           2       0           2            0
## Peter                0        1           1       0           1            0
## Apothecary           0        0           0       0           0            0
## Balthasar            0        0           1       0           1            0
## Boy                  0        0           1       0           1            0
## PageToParis          0        0           1       0           1            0
##                LordMontague PrinceEscalus Romeo Sampson Tybalt CountParis
## Abraham                   1             1     1       1      1          0
## Benvolio                  2             2     7       1      3          1
## LordCapulet               2             2     5       1      2          4
## Gregory                   1             1     1       1      1          0
## LadyCapulet               3             3     4       1      2          3
## LadyMontague              1             1     1       1      1          0
## LordMontague              3             3     3       1      2          1
## PrinceEscalus             3             3     3       1      2          1
## Romeo                     3             3    14       1      3          2
## Sampson                   1             1     1       1      1          0
## Tybalt                    2             2     3       1      3          0
## CountParis                1             1     2       0      0          5
## CapuletServant            0             0     2       0      1          1
## Juliet                    1             1     5       0      1          2
## Nurse                     0             0     5       0      1          1
## Mercutio                  1             1     4       0      1          0
## Chorus                    0             0     1       0      1          0
## Friar                     1             1     4       0      0          3
## Peter                     0             0     1       0      0          1
## Apothecary                0             0     1       0      0          0
## Balthasar                 1             1     2       0      0          1
## Boy                       1             1     1       0      0          1
## PageToParis               1             1     1       0      0          1
##                CapuletServant Juliet Nurse Mercutio Chorus Friar Peter
## Abraham                     0      0     0        0      0     0     0
## Benvolio                    2      1     2        4      1     0     1
## LordCapulet                 2      4     5        0      1     2     1
## Gregory                     0      0     0        0      0     0     0
## LadyCapulet                 1      5     5        1      0     2     1
## LadyMontague                0      0     0        0      0     0     0
## LordMontague                0      1     0        1      0     1     0
## PrinceEscalus               0      1     0        1      0     1     0
## Romeo                       2      5     5        4      1     4     1
## Sampson                     0      0     0        0      0     0     0
## Tybalt                      1      1     1        1      1     0     0
## CountParis                  1      2     1        0      0     3     1
## CapuletServant              3      2     2        0      1     0     0
## Juliet                      2     11     7        0      1     3     0
## Nurse                       2      7    11        1      1     2     2
## Mercutio                    0      0     1        4      0     0     1
## Chorus                      1      1     1        0      1     0     0
## Friar                       0      3     2        0      0     6     1
## Peter                       0      0     2        1      0     1     2
## Apothecary                  0      0     0        0      0     0     0
## Balthasar                   0      1     0        0      0     1     0
## Boy                         0      1     0        0      0     1     0
## PageToParis                 0      1     0        0      0     1     0
##                Apothecary Balthasar Boy PageToParis
## Abraham                 0         0   0           0
## Benvolio                0         0   0           0
## LordCapulet             0         1   1           1
## Gregory                 0         0   0           0
## LadyCapulet             0         1   1           1
## LadyMontague            0         0   0           0
## LordMontague            0         1   1           1
## PrinceEscalus           0         1   1           1
## Romeo                   1         2   1           1
## Sampson                 0         0   0           0
## Tybalt                  0         0   0           0
## CountParis              0         1   1           1
## CapuletServant          0         0   0           0
## Juliet                  0         1   1           1
## Nurse                   0         0   0           0
## Mercutio                0         0   0           0
## Chorus                  0         0   0           0
## Friar                   0         1   1           1
## Peter                   0         0   0           0
## Apothecary              1         1   0           0
## Balthasar               1         2   1           1
## Boy                     0         1   1           1
## PageToParis             0         1   1           1

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.

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.

Modifying networks

To add information to a simple network graph, we create 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("Prince", "Paris", "Mercutio")
capulet <- c("Capulet", "Ladycapulet", "Juliet", "Tybalt", "Nurse",
             "Peter", "Gregory", "Sampson", "Anthony",  "Servant",
             "Servant")
montague <- c("Montague", "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
network::set.edge.attribute(net, "weights", ifelse(net %e% "weights" <= 1, 0.25, 
                                   ifelse(net %e% "weights" <= 3, .5, 1)))
# define line type
network::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.

2 Creating networks with quanteda

The quanteda package contains many very useful functions for analyzing texts. Among these functions is the textplot_network function which provides a very handy way to display networks.

We could simply start with the romeo data that we have processed above. However, as the quanteda package offers useful text processing functions, we will start with the personas data set that we have created before so as to show how handy and easy to use the quanteda functions are. In a first step, we transform the text vectors of the persons data into a document-feature matrix using the dfm function.

library(quanteda)
romeo_dfm <- as.dfm(romeo)
romeo_fcm <- fcm(romeo_dfm)
head(romeo_fcm)
## Feature co-occurrence matrix of: 6 by 6 features.
##               features
## features       Abraham Benvolio LordCapulet Gregory LadyCapulet LadyMontague
##   Abraham            0       30          34      11          35           11
##   Benvolio           0       59         139      30         130           30
##   LordCapulet        0        0          97      34         246           34
##   Gregory            0        0           0       0          35           11
##   LadyCapulet        0        0           0       0         104           35
##   LadyMontague       0        0           0       0           0            0

This feature-co-occurrence matrix can then serve as the input for the textplot_network function which already generates a nice network graph.

textplot_network(romeo_fcm, min_freq = 0.1, edge_alpha = 0.1, edge_size = 5)

The network graph can then be modified or customized easily by defining the arguments of the textplot_network fucntion. To see how and which aguments can be modified, you can use ?textplot_network.

textplot_network(romeo_fcm, min_freq = 2, 
                 edge_alpha = 0.2, 
                 edge_color = "orange", 
                 edge_size = 5)

3 Creating networks with iGraph

Wiedemann and Niekler (2017) have written a very recommendable tutorial on co-occurrence analysis and they propose an alternative, yet more complex network visualization for co-occurrences. Their approach is to create and customize a graph object based on the iGraph package. To see how to cerate sophisticated network graphs using the iGraph package, see this tutorial on analyzing collocations or this tutorial.

4 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" = "orange", "event" = "lightblue")
ggnet2(ajn, 
       color = "mode", 
       shape = "mode",
       size = 7,
       alpha = 0.7,
       palette = clrs,
       label.size = 5,
       label.color = "black",
       label = TRUE, 
       edge.size = "weights",
       edge.alpha = 0.3) +
  theme(panel.background = element_rect(fill = "white"))
## Warning: Duplicated override.aes is ignored.

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 interested in General Linguistics. Ilana has ties to both JPrag and Language but the thickness of the lines suggest that she too is more interested in Pragmatocs while also dealing with General Linguistics.

Finally, you can inspect 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 1.0000000 0.6289059
## 2  Michael   0.7 actor actor    5 0.7503098 0.0000000
## 3 Felicity   0.7 actor actor    5 0.4403793 0.8326979
## 4    Ilana   0.7 actor actor    5 0.1009732 0.3595151
## 5    JPrag   0.7 event event    5 0.5877890 0.4018090
## 6 Language   0.7 event event    5 0.0000000 0.7446101
## 7   Lingua   0.7 event event    5 0.8514774 1.0000000

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

Citation & Session Info

Schweinberger, Martin. 2020. Network Analysis using R. Brisbane: The University of Queensland. url: https://slcladal.github.io/net.html (Version 2020.09.29).

@manual{schweinberger2020net,
  author = {Schweinberger, Martin},
  title = {Network Analysis using R},
  note = {https://slcladal.github.io/net.html},
  year = {2020},
  organization = "The University of Queensland, Australia. School of Languages and Cultures},
  address = {Brisbane},
  edition = {2020/09/28}
}
sessionInfo()
## R version 4.0.3 (2020-10-10)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19041)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252   
## [3] LC_MONETARY=German_Germany.1252 LC_NUMERIC=C                   
## [5] LC_TIME=German_Germany.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] quanteda_2.1.2       Matrix_1.2-18        tm_0.7-7            
##  [4] NLP_0.2-1            gutenbergr_0.2.0     kableExtra_1.3.1    
##  [7] knitr_1.30           sna_2.6              statnet.common_4.4.1
## [10] forcats_0.5.0        stringr_1.4.0        dplyr_1.0.2         
## [13] purrr_0.3.4          readr_1.4.0          tidyr_1.1.2         
## [16] tibble_3.0.4         tidyverse_1.3.0      network_1.16.1      
## [19] GGally_2.0.0         ggplot2_3.3.2       
## 
## loaded via a namespace (and not attached):
##  [1] httr_1.4.2         jsonlite_1.7.1     viridisLite_0.3.0  modelr_0.1.8      
##  [5] RcppParallel_5.0.2 assertthat_0.2.1   cellranger_1.1.0   ggrepel_0.8.2     
##  [9] yaml_2.2.1         slam_0.1-47        pillar_1.4.6       backports_1.1.10  
## [13] lattice_0.20-41    glue_1.4.2         digest_0.6.27      RColorBrewer_1.1-2
## [17] rvest_0.3.6        colorspace_1.4-1   htmltools_0.5.0    plyr_1.8.6        
## [21] pkgconfig_2.0.3    broom_0.7.2        haven_2.3.1        scales_1.1.1      
## [25] webshot_0.5.2      generics_0.1.0     farver_2.0.3       usethis_1.6.3     
## [29] ellipsis_0.3.1     withr_2.3.0        cli_2.1.0          magrittr_1.5      
## [33] crayon_1.3.4       readxl_1.3.1       evaluate_0.14      stopwords_2.0     
## [37] fs_1.5.0           fansi_0.4.1        xml2_1.3.2         tools_4.0.3       
## [41] data.table_1.13.2  hms_0.5.3          lifecycle_0.2.0    munsell_0.5.0     
## [45] reprex_0.3.0       compiler_4.0.3     rlang_0.4.8        grid_4.0.3        
## [49] rstudioapi_0.11    rmarkdown_2.5      gtable_0.3.0       DBI_1.1.0         
## [53] reshape_0.8.8      R6_2.5.0           rle_0.9.2          lubridate_1.7.9   
## [57] fastmatch_1.1-0    stringi_1.5.3      parallel_4.0.3     Rcpp_1.0.5        
## [61] vctrs_0.3.4        dbplyr_2.0.0       tidyselect_1.1.0   xfun_0.19         
## [65] coda_0.19-4

References


Main page


Silge, Julia, and David Robinson. 2017. Text Mining with R: A Tidy Approach. " O’Reilly Media, Inc.".

Wiedemann, Gregor, and Andreas Niekler. 2017. “Hands-on: A Five Day Text Mining Course for Humanists and Social Scientists in R.” In Proceedings of the Workshop on Teaching NLP for Digital Humanities (Teach4DH@GSCL 2017), Berlin, Germany, September 12, 2017., 57–65. http://ceur-ws.org/Vol-1918/wiedemann.pdf.