-
Notifications
You must be signed in to change notification settings - Fork 0
/
intro_tidygraph_ggraph.html
991 lines (799 loc) · 34.2 KB
/
intro_tidygraph_ggraph.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
<!DOCTYPE html>
<html lang="" xml:lang="">
<head>
<title>MAT381E-Week 10: Creating and Visualizing Networks</title>
<meta charset="utf-8" />
<meta name="author" content="Gül İnan" />
<meta name="date" content="2021-12-13" />
<script src="intro_tidygraph_ggraph_files/header-attrs-2.11/header-attrs.js"></script>
<link href="intro_tidygraph_ggraph_files/remark-css-0.0.1/default.css" rel="stylesheet" />
<script src="intro_tidygraph_ggraph_files/fabric-4.3.1/fabric.min.js"></script>
<link href="intro_tidygraph_ggraph_files/xaringanExtra-scribble-0.0.1/scribble.css" rel="stylesheet" />
<script src="intro_tidygraph_ggraph_files/xaringanExtra-scribble-0.0.1/scribble.js"></script>
<script>document.addEventListener('DOMContentLoaded', function() { window.xeScribble = new Scribble({"pen_color":["#FF0000"],"pen_size":3,"eraser_size":30,"palette":[]}) })</script>
<link href="intro_tidygraph_ggraph_files/tile-view-0.2.6/tile-view.css" rel="stylesheet" />
<script src="intro_tidygraph_ggraph_files/tile-view-0.2.6/tile-view.js"></script>
<link href="intro_tidygraph_ggraph_files/animate.css-3.7.2/animate.xaringan.css" rel="stylesheet" />
<link href="intro_tidygraph_ggraph_files/tachyons-4.12.0/tachyons.min.css" rel="stylesheet" />
<link href="intro_tidygraph_ggraph_files/panelset-0.2.6/panelset.css" rel="stylesheet" />
<script src="intro_tidygraph_ggraph_files/panelset-0.2.6/panelset.js"></script>
<link rel="stylesheet" href="xaringan-themer.css" type="text/css" />
<link rel="stylesheet" href="assets/sydney-fonts.css" type="text/css" />
<link rel="stylesheet" href="assets/sydney.css" type="text/css" />
</head>
<body>
<textarea id="source">
class: left, middle, my-title, title-slide
# MAT381E-Week 10: Creating and Visualizing Networks
### Gül İnan
### Department of Mathematics<br/>Istanbul Technical University
### December 13, 2021
---
class: left
# Outline
* What is Network?
* Examples
* Elements of a graph.
* The `tidygraph` and `ggraph` packages.
---
# Graph Elements
- A graph `\(\mathcal{G}\)` consists of two sets:
- The first set `\(\mathcal{V}\)`
is known as the **vertex set** or **node set**, and consists of vertices.
- The second set `\(\mathcal{E}\)`
is known as the **edge set**, and consists of pairs of elements of `\(\mathcal{V}\)`.
- Given that a graph is made up of these two sets, we will often notate our graph as
`\(\mathcal{G} = (\mathcal{V}, \mathcal{E})\)`.
- If two vertices appear as a pair in `\(\mathcal{E}\)`, then those vertices are said to be **adjacent** or **connected vertices**.
---
# Example
- Following figure is a diagram of a graph `\(\mathcal{G}_{work}\)`
with **four vertices** representing four people.
- An **edge connects two vertices** if and only if those two people have worked together.
<img src="images/gwork.png" width="40%" height="40%" style="display: block; margin: auto;" />
- The vertex set `\(\mathcal{V}\)` for the graph `\(\mathcal{G}_{work}\)` is:
`\begin{equation}
\mathcal{V} = \{David, Suraya, Jane, Zubin\}
\end{equation}`
- The edge set `\(\mathcal{E}\)` can be denoted in different ways. One approach is to use set notation:
`\begin{equation}
\mathcal{E} = \{ \{David, Zubin\}, \{David, Suraya\}, \{David, Jane\}, \{Jane, Zubin\}, \{Jane, Suraya\} \}
\end{equation}`
---
- Note that if David has worked with Zubin, then we can automatically say that Zubin has worked with David.
- Therefore, we do not need for **direction in the edges** of `\(\mathcal{G}_{work}\)`.
- The order of the nodes in each pair in the edge set `\(\mathcal{E}\)` is not relevant.
- We call such a graph as an **undirected graph**.
- In an **undirected graph**, following two sets are the same:
`\begin{equation}
\mathcal{E} = \{ \{David, Zubin\}, \{David, Suraya\}, \{David, Jane\}, \{Jane, Zubin\}, \{Jane, Suraya\} \}.
\end{equation}`
`\begin{equation}
\mathcal{E} = \{ \{Zubin, David\}, \{Suraya, Suraya\}, \{Jane, David\}, \{Zubin, Jane\}, \{Suraya, Jane\} \}.
\end{equation}`
- Alternatively, we can also use:
`\begin{equation}
\mathcal{E} = \{ \{David \leftrightarrow Zubin\}, \{David \leftrightarrow Suraya\}, \{David \leftrightarrow Jane\}, \{Jane \leftrightarrow Zubin\}, \{Jane \leftrightarrow Suraya\} \}.
\end{equation}`
- As long as the vertex and edge sets contains all of the information required to construct the graph, it does not matter how you notate them.
---
- A graph where **direction is important** is called a **directed graph**.
- As an example, let’s consider a graph `\(\mathcal{G}_{manage}\)` with the same vertex set of four people but where an edge exists between two people if and only if the first person is the manager of the second person, as in the following figure:
<img src="images/gmanage.png" width="40%" height="40%" style="display: block; margin: auto;" />
- Since the direction matters in this example, we may wish to notate the edge set `\(\mathcal{E}\)`
for `\(\mathcal{G}_{manage}\)` as follows:
`\begin{equation}
\mathcal{E} = \{ \{Sureaya \rightarrow David\}, \{David \rightarrow Zubin\}, \{David \rightarrow Jane\}\}.
\end{equation}`
---
- The graphs `\(\mathcal{G}_{work}\)` and `\(\mathcal{G}_{manage}\)`
are called **simple graphs**.
- A simple graph cannot have **more than one edge** between any two vertices, and cannot have any **loop** edges from one vertex back to itself.
- A **multigraph** is a graph where **multiple edges** can occur between the **same two vertices**. Usually this occurs because the edges are defining different kinds of relationships.
- Travel routes are common examples of multigraphs, where each edge represents a different carrier.
<img src="images/gmap.png" width="60%" height="60%" style="display: block; margin: auto;" />
---
#### Adjacency matrix
- While **networks** are visually displayed as **graphs**, most network analysis software/packages need data to be prepared as **adjacency matrices**.
- An adjacency matrix is a **square matrix** in which the **column and row names** are the vertices of the network, and where the `\((i,j)\)`-th entry of the matrix represents the number of edges from vertex `\(i\)` to vertex `\(j\)`.
- Within the adjacency matrix a **1 indicates** that there is a **connection between the vertices**, and a **0 indicates no connection**.
- As an example, using our graph `\(\mathcal{G}_{work}\)` the adjacency matrix would look like this:
.pull-left[
<img src="images/gwork.png" width="100%" height="100%" />
]
.pull-right[
<img src="images/adj_matrix1.png" width="100%" height="100%" />
]
---
#### How to create Network objects in R?
- Unfortunately, adjacency matrices implement a very **different data structure** than the `tidyverse workflow` that we have used so far.
- Hopefully, we can create **network objects** from an **edge-list data frame**, which do fit in the `tidyverse workflow`.
- An **edge list** is a **data frame** that contains a **minimum of two columns**:
- One column of nodes (vertices) that are the **source of a connection**, also labelled as **from** and
- Another column of nodes that are the **target of the connection**, also labelled as **to**.
- For example, the edge list for graph `\(\mathcal{G}_{work}\)` would like as follows:
<img src="images/edge_list.png" width="60%" height="60%" style="display: block; margin: auto;" />
---
- An edge list can also contain **additional columns** that describe **attributes of the edges** such as a magnitude aspect for an edge.
- If the edges have a **magnitude attribute** the graph is considered **weighted**.
- The **nodes** in the data are identified by **unique IDs**.
---
- Let's create the minimal edge list for graph `\(\mathcal{G}_{work}\)` with the `tibble()` function.
- We will name the source column as “from” and the target column as “to”.
```r
library(tidyverse)
gwork_edgelist <- tibble(
from = c("David", "David", "David", "Jane", "Jane"),
to = c("Zubin", "Suraya", "Jane", "Zubin", "Suraya")
)
gwork_edgelist
```
```
#> # A tibble: 5 × 2
#> from to
#> <chr> <chr>
#> 1 David Zubin
#> 2 David Suraya
#> 3 David Jane
#> 4 Jane Zubin
#> 5 Jane Suraya
```
---
- How can we know that how many nodes (vertices) we have?
```r
###Create the unique node list
source <- gwork_edgelist %>%
distinct(from) %>%
rename(label = from) #rename it by label
target <- gwork_edgelist %>%
distinct(to) %>%
rename(label = to) #rename it by label
#number of nodes
nodes <- full_join(source, target, by = "label") #removes repeated entries
dim(nodes)[1]
```
```
#> [1] 4
```
---
class: center, middle
# Centrality measures
---
#### Centrality degree
- The **degree centrality** or **valence** of a vertex _v_ is the number of edges connected to _v_.
- **Degree centrality** is a measure of **immediate connection in a network** and could be interpreted as **immediate reach in a social network**. Its precise interpretation depends strongly on the nature of the connection.
<img src="images/centrality.png" width="50%" height="50%" style="display: block; margin: auto;" />
- Vertex 4 has the highest degree centrality.
---
#### Closeness centrality
- The closeness centrality of a vertex _v_ in a connected graph is the **inverse of the sum of the distances** from _v_ to all other vertices.
- Inverting this distance means that **lower total distances** will generate **higher closeness centrality**.
- **Closeness centrality** is a measure of **how efficiently** the entire graph can be traversed from a given vertex. This is particularly valuable in the study of **information flow**. In social networks, information shared by those with high closeness centrality will likely reach the entire network more efficiently.
<img src="images/centrality.png" width="50%" height="50%" style="display: block; margin: auto;" />
- Vertex 7 has the highest closeness centrality.
---
#### Betwenness centrality
- The **betweenness centrality** of a vertex _v_
is calculated by taking each pair of other vertices _x_ and _y_, calculating the number of shortest paths between _x_ and _y_ that go through _v_ dividing by the total number of shortest paths between _x_ and _y_ then summing over all such pairs of vertices in the graph.
- **Betweenness centrality** is a measure of how important a given vertex is in connecting other pairs of vertices in the graph.
- In people networks, individuals with higher betweenness centrality can be regarded as playing important roles in ensuring overall connectivity of the network, and if they are removed from the network the risks of overall disconnection are higher. This has strong applications in studying the effects of departures from organizations.
<img src="images/centrality.png" width="30%" height="30%" style="display: block; margin: auto;" />
- Vertex 9 has the highest betweenness centrality.
---
#### Which measure are they estimating?
<a href="https://research.fb.com/blog/2016/02/three-and-a-half-degrees-of-separation/" target="_blank"><img src="images/facebook.png" width="70%" height="70%" style="display: block; margin: auto;" /></a>
- **Side note:** "We used [_Flajolet-Martin’s math_](https://en.wikipedia.org/wiki/Flajolet%E2%80%93Martin_algorithm) to estimate the number of unique friends for each degree of separation."
---
#### The igraph software/package
- The [igraph](https://igraph.org/) is a collection of network analysis tools for visualizing and summarizing graphs.
- It has front-ends for `R`, `Python`, `Mathematica`, and `C/C++`.
- For example, the `R` package to use [igraph](https://igraph.org/) software is
the [igraph](https://igraph.org/r/) package.
- However, its data structure is not compatible with `tidyverse ecosytem`.
<br>
<img src="logo/igraph.png" width="50%" height="50%" style="display: block; margin: auto 0 auto auto;" />
---
class: middle, center
.pull-left[
<img src="logo/tidygraph.png" width="60%" height="100%" />
]
.pull-right[
<img src="logo/ggraph.png" width="60%" height="100%" />
]
---
#### tidygraph and ggraph packages
- The [tidygraph](https://tidygraph.data-imaginist.com/) and [ggraph](https://www.data-imaginist.com/2017/ggraph-introduction-layouts/) packages leverage the power of [igraph](https://igraph.org/r/) in a manner consistent with the `tidyverse ecosystem`.
- Of course, to be able to use the functionalities of `tidygraph` and `ggraph` packages, we have to install and then load the packages:
```r
## Download and install the packages
## install.packages(c("tidygraph","ggraph"))
## load the packages
library(tidygraph)
library(ggraph)
```
---
#### tidygraph package
- The [tidygraph](https://tidygraph.data-imaginist.com/) provides an tidy API for graph/network manipulation. While network data itself is not tidy, it can be envisioned as **two tidy tables**, one for **node data** and one for **edge data**.
- It basically provides a way to **switch between** the edge and node **tables** and accepts `dplyr` functions for manipulating them.
- Most commonly used functions in the `tidygraph` package are:
|Function |Description |
|-----------------------------|------------------------------------------------------------------------------------|
|`as_tbl_graph()` |Create a data structure from edge list for tidy graph manipulation. |
|`tbl_graph()` |Create a data structure from edge list for tidy graph manipulation when node list is also available. |
|`activate()` |Defines whether to manipulate node or edge table at the moment. Takes either `nodes` or `edges` keyword.|
|`centrality_*()` | Measures the importance of node in the network with different centrality measures. Used inside `dplyr::mutate()`.|
|`bind_edges()` | Append edges to the graph. New data must contain valid **from** and **to** columns.|
|`bind_nodes()` | Append nodes to the graph. |
|`bind_graphs()` | Combine multiple graphs in the same graph structure resulting in each original graph to become a component in the returned graph.|
---
#### Example: Bitcoin Alpha trust weighted signed network
- **Dataset information:** This is who-trusts-whom network of people who trade using Bitcoin on a platform called Bitcoin Alpha. Since Bitcoin users are **anonymous**, there is a need to maintain a record of users' reputation to prevent transactions with fraudulent and risky users. Members of Bitcoin Alpha rate other members in a scale of -10 (total distrust) to +10 (total trust) in steps of 1. This is the first explicit weighted signed directed network available for research.
- The data set is said to be available at https://snap.stanford.edu/data/soc-sign-bitcoin-alpha.html.
- However, I was able to download the data from the following source: https://cs.stanford.edu/~srijan/wsn/.
<img src="images/dataformat.png" width="90%" height="100%" />
---
<img src="images/bitcoin.png" width="50%" height="100%" />
---
- We should first import the bitcoin data.
```r
#import data with read_csv
library(tidyverse)
#there is no column names.
#first label the columns.
bitcoin <- read_csv("data/BTCAlphaNET.csv", col_names = c("Source", "Target", "Rating"))
head(bitcoin, 10)
```
```
#> # A tibble: 10 × 3
#> Source Target Rating
#> <dbl> <dbl> <dbl>
#> 1 2 402 0.1
#> 2 10 970 0.8
#> 3 113 54 0.4
#> 4 10 271 0.8
#> 5 119 2 0.8
#> 6 119 54 0.5
#> 7 119 271 0.8
#> 8 54 119 0.5
#> 9 119 471 0.9
#> 10 168 74 0.1
```
---
- Check the the number of edges and nodes in the data set, respectively.
```r
#check the number of edges
dim(bitcoin)
```
```
#> [1] 24186 3
```
```r
#check the number of distinct sources
#3286
bitcoin %>%
distinct(Source) %>%
count()
```
```
#> # A tibble: 1 × 1
#> n
#> <int>
#> 1 3286
```
```r
#check the number of distinct targets
#3754
bitcoin %>%
distinct(Target) %>%
count()
```
```
#> # A tibble: 1 × 1
#> n
#> <int>
#> 1 3754
```
---
- Now create unique node list to determine the number of nodes.
```r
### Create the unique node list
#3286
sources <- bitcoin %>%
distinct(Source) %>%
rename(label = Source)
#3754
targets <- bitcoin %>%
distinct(Target) %>%
rename(label = Target)
# 3783
nodes <- full_join(sources, targets, by = "label")
dim(nodes)
```
```
#> [1] 3783 1
```
---
#### Prepare an edge list
- Edge list is a simple data frame with **two columns**, with a ‘from’ and a ‘to’, representing the connections between two nodes, one per row.
- We can add an **attribute** called weight to the edge list, which is simply another column.
```r
#Now create edge list.
#note that bitcoin data already came in this format.
edges <- bitcoin %>%
rename(from = Source, to = Target, weight = Rating)
#View(edges)
```
---
#### Turn the edge list into a graph object: tbl_graph()
- The function `as_tbl_graph()` in `tidygraph` package turns the edge list into a graph object with `tbl_graph` class.
```r
library(tidygraph)
bitcoin_tbl_graph <- edges %>%
as_tbl_graph()
class(bitcoin_tbl_graph)
```
```
#> [1] "tbl_graph" "igraph"
```
---
- The returned `tbl_graph` object consists of **two tables**, one for the nodes and one for the edges.
```r
bitcoin_tbl_graph
```
```
#> # A tbl_graph: 3783 nodes and 24186 edges
#> #
#> # A directed simple graph with 5 components
#> #
#> # Node Data: 3,783 × 1 (active)
#> name
#> <chr>
#> 1 2
#> 2 10
#> 3 113
#> 4 119
#> 5 54
#> 6 168
#> # … with 3,777 more rows
#> #
#> # Edge Data: 24,186 × 3
#> from to weight
#> <int> <int> <dbl>
#> 1 1 41 0.1
#> 2 2 3287 0.8
#> 3 3 5 0.4
#> # … with 24,183 more rows
```
- The `tbl_graph` class allows us to use `tidyverse ecosystem` functions to manipulate the `graph` objects along with the `igraph` package functions.
- This means we can create a network and then use a range of standard data analysis functions on it as needed.
---
- We can access each of the tables using the function `activate(nodes)` or `activate(edges)`. The active table has the word `(active)` next to it.
- Activate nodes data:
```r
bitcoin_tbl_graph %>%
activate(nodes)
```
```
#> # A tbl_graph: 3783 nodes and 24186 edges
#> #
#> # A directed simple graph with 5 components
#> #
#> # Node Data: 3,783 × 1 (active)
#> name
#> <chr>
#> 1 2
#> 2 10
#> 3 113
#> 4 119
#> 5 54
#> 6 168
#> # … with 3,777 more rows
#> #
#> # Edge Data: 24,186 × 3
#> from to weight
#> <int> <int> <dbl>
#> 1 1 41 0.1
#> 2 2 3287 0.8
#> 3 3 5 0.4
#> # … with 24,183 more rows
```
---
- The current **active data table** can always be extracted as a **tibble** using `as_tibble()`:
```r
bitcoin_tbl_graph %>%
activate(nodes) %>%
as_tibble()
```
```
#> # A tibble: 3,783 × 1
#> name
#> <chr>
#> 1 2
#> 2 10
#> 3 113
#> 4 119
#> 5 54
#> 6 168
#> 7 271
#> 8 474
#> 9 37
#> 10 99
#> # … with 3,773 more rows
```
---
- Activate edges data:
```r
bitcoin_tbl_graph %>%
activate(edges)
```
```
#> # A tbl_graph: 3783 nodes and 24186 edges
#> #
#> # A directed simple graph with 5 components
#> #
#> # Edge Data: 24,186 × 3 (active)
#> from to weight
#> <int> <int> <dbl>
#> 1 1 41 0.1
#> 2 2 3287 0.8
#> 3 3 5 0.4
#> 4 2 7 0.8
#> 5 4 1 0.8
#> 6 4 5 0.5
#> # … with 24,180 more rows
#> #
#> # Node Data: 3,783 × 1
#> name
#> <chr>
#> 1 2
#> 2 10
#> 3 113
#> # … with 3,780 more rows
```
---
- Get edges data:
```r
bitcoin_tbl_graph %>%
activate(edges) %>%
as_tibble()
```
```
#> # A tibble: 24,186 × 3
#> from to weight
#> <int> <int> <dbl>
#> 1 1 41 0.1
#> 2 2 3287 0.8
#> 3 3 5 0.4
#> 4 2 7 0.8
#> 5 4 1 0.8
#> 6 4 5 0.5
#> 7 4 7 0.8
#> 8 5 4 0.5
#> 9 4 17 0.9
#> 10 6 20 0.1
#> # … with 24,176 more rows
```
---
- The `tidygraph` allows us to perform centrality calculations on the `tbl_graph` object for use inside `dplyr::mutate()`.
- The function `centrality_degree()` calculates the degree of every node and returns a numeric vector giving the centrality measure of each node.
- For example to calculate the degree of every node in the bitcoin example:
```r
#sort the nodes by their degree (in descending form)
node_degree <- bitcoin_tbl_graph %>%
activate(nodes) %>%
mutate(degree = centrality_degree()) %>% #returns degree column in an active node table
as_tibble() %>% #get node table
arrange(-degree)
#View(node_degree)
```
- The more connections a node have the more it is more central and highly connected, thus it has an **influence on the graph**.
---
- Find the most reliable people on this network!..
```r
bitcoin_tbl_graph %>%
activate(edges) %>%
filter(weight == 1) %>% #find who gets 1
as_tibble() %>%
count(to) #%>% #count how many 1's received that person
#View()
```
---
- If we want to filter just edges from ID 1, we can use the `filter()` function from `dplyr` and create a new graph object with `as_tbl_graph()`:
```r
trader_1 <- bitcoin_tbl_graph %>%
activate(edges) %>%
filter(from == 1) %>%
as_tbl_graph()
#View(trader_34)
```
```r
trader_1 %>%
as_tibble() #%>%
```
```
#> # A tibble: 195 × 3
#> from to weight
#> <int> <int> <dbl>
#> 1 1 41 0.1
#> 2 1 12 0.1
#> 3 1 6 0.9
#> 4 1 11 0.2
#> 5 1 2 0.3
#> 6 1 26 0.2
#> 7 1 31 0.1
#> 8 1 29 0.2
#> 9 1 45 0.1
#> 10 1 20 0.6
#> # … with 185 more rows
```
```r
#View()
```
---
- Calculate the centrality of betwenness in the bitcoin network.
```r
node_betweennes <- bitcoin_tbl_graph %>%
activate(nodes) %>%
mutate(betweenness = centrality_betweenness()) %>%
as_tibble() %>%
arrange(-betweenness)
#View(node_betwenness)
```
---
#### Expanding graphs: Binding edges
- The function `bind_edges()` append edges to an existing graph.
- Trader "1" did not trade with traders "22" and "23". But, let's assume
that they have actually traded, but, we forgot to record it.
```r
edge2 <- tibble(from = c(1, 1), to = c(22, 23), weight= c(0.8,0.8))
```
```r
bitcoin_tbl_graph %>%
activate(edges) %>%
bind_edges(edge2) %>%
filter(from == 1) %>%
as_tibble() %>%
View()
```
---
#### Newtwork visualisation with ggraph
- The [ggraph](https://github.com/thomasp85/ggraph) package provides a grammar for building **network visualizations**.
- The `ggraph` package uses the same language as `ggplot2` so that making it easier to carry over basic `ggplot` skills to the creation of network plots.
- It also adds some special `geoms` to the basic set of `ggplot` `geoms` that are specifically designed for networks.
- In all network graphs there are _three main aspects_ for a `ggraph` plot:
- [nodes](https://www.data-imaginist.com/2017/ggraph-introduction-nodes/),
- [edges](https://www.data-imaginist.com/2017/ggraph-introduction-edges/), and
- [layouts](https://www.data-imaginist.com/2017/ggraph-introduction-layouts/).
---
- To create a network diagram, first we need to use the function `ggraph()` on our `tbl_graph` object,
then add the special ggraph based `geom_*()` such as:
|Function |Description |
|-------------------|------------------------------------------------------------------------|
|`ggraph()` | Takes the data to be used for the graph and the **type of layout** desired. |
|`geom_node_*()` | Draw nodes. Many of these are direct translations of ggplot2. |
|`geom_edge_*()` | Draw edges. |
|`theme_graph()` | Special ggplot theme that provides better defaults for network graphs. |
---
- Let’s see what a basic `ggraph()` plot looks like. The plot begins with `ggraph()` and the data.
- The structure of the `ggraph()` is similar to that of `ggplot` with the separate layers added with the + sign.
- Then we add basic node and edge geoms such as `geom_node_point()` and `geom_edge_link()`, respectively, with the + sign.
- No arguments are necessary within the edge and node geoms, because they take the information from the data provided in `ggraph()`.
- But, the functions `geom_node_point()` and `geom_edge_link()` take aesthetics, just like regular `ggplot geoms`.
---
.panelset[
.panel[.panel-name[Code]
```r
library(ggraph)
bitcoin_tbl_graph %>%
activate(nodes) %>%
mutate(degree = centrality_degree()) %>%
filter(60 < degree & degree < 80) %>% #filter traders with whose degree is between 60 and 80.
#activate(nodes) %>% #returns a tbl_graph with 21 nodes and 68 edges
ggraph(layout = "auto") + #default one
geom_node_point(shape = 1, size = 2, colour = "blue") + #?geom_node_point for more aesthetics
geom_edge_link(edge_colour="red") + #?geom_edge_link for more aesthetics
#This geom draws edges in the simplest way - as straight lines between the start and end nodes.
theme_graph() +#if i do not use then background color will be gray.
labs(title = "Bitcoin Alpha trust Network")
```
]
.panel[.panel-name[Output]
![](intro_tidygraph_ggraph_files/figure-html/unnamed-chunk-40-1.png)<!-- -->
]
]
---
.panelset[
.panel[.panel-name[Code]
- Add `geom_node_text()` to add text labels to your network. In a larger network,
it can be helpful to only show labels belonging to the most-connected nodes.
```r
bitcoin_tbl_graph %>%
activate(nodes) %>%
mutate(degree = centrality_degree()) %>%
filter(60 < degree & degree < 80) %>%
#activate(nodes) %>%
ggraph(layout = "auto") + #default one
geom_edge_link(edge_colour="red") +
geom_node_point(aes(size = as.factor(degree))) + #resize nodes with respect to degree
#geom_node_text(aes(label = name), repel = TRUE) +
geom_node_text(aes(label = if_else(degree > 75, name, NULL)), repel = TRUE) + #name colum comes from nodes table
#set to TRUE will use the repel functionality provided by
#the ggrepel package to avoid overlapping text.
theme_graph() +
labs(title = "Bitcoin Alpha trust Network")
```
- The a `repel = TRUE` argument ensures that the labels do not overlap with the nodes.
]
.panel[.panel-name[Output]
![](intro_tidygraph_ggraph_files/figure-html/unnamed-chunk-42-1.png)<!-- -->
]
]
---
- A **layout** is the vertical and horizontal placement of nodes when plotting a particular graph structure.
- More is available at https://www.data-imaginist.com/2017/ggraph-introduction-layouts/.
.panelset[
.panel[.panel-name[Code]
```r
bitcoin_tbl_graph %>%
activate(nodes) %>%
mutate(degree = centrality_degree()) %>%
filter(60 < degree & degree < 80) %>% #note in between(degree,60,80): end-points are included
ggraph(layout = 'dendrogram') +
geom_node_text(aes(label = name), repel = TRUE) +
geom_node_point(shape = 1, size = 2, colour = "darkblue") +
geom_edge_diagonal(colour = 'red') +
theme_graph()
```
]
.panel[.panel-name[Output]
![](intro_tidygraph_ggraph_files/figure-html/unnamed-chunk-44-1.png)<!-- -->
]
]
---
- For **dynamic network visualization**:
<a href="http://christophergandrud.github.io/networkD3/" target="_blank"><img src="images/networkd3.png" width="80%" height="100%" style="display: block; margin: auto;" /></a>
---
class: center, middle
<img src="images/done.png" width="80%" height="100%" />
---
- More is available at:
- [Handbook of Graphs and Networks in People Analytics](https://ona-book.org/gitbook/).
- [Awesome list curated by François Briatte](https://github.com/briatte/awesome-network-analysis).
- [Katya Ognyanova's Network Visualization with R](http://kateto.net/network-visualization).
- [Douglas A. Luke, *A User’s Guide to Network Analysis in R* (2015)](http://www.springer.com/us/book/9783319238821).
- [Eric D. Kolaczyk and Gábor Csárdi's, Statistical Analysis of Network Data with R (2014)](http://www.springer.com/us/book/9781493909827).
---
# Attributions
- All images used in this slide are taken from the web.
- This lecture note is mainly developed by following sources:
- [Source 1](http://veronikarock.com/teaching/06_slides.pdf),
- [Source 2](https://www.jessesadler.com/post/network-analysis-with-r/),
- [Source 3](http://users.dimi.uniud.it/~massimo.franceschet/ns/syllabus/make/tidygraph/tidygraph.html),
- [Source 4](https://towardsdatascience.com/notes-on-graph-theory-centrality-measurements-e37d2e49550a), and
- [Source 5](https://networkingarchives.github.io/blog/2021/04/15/my-network-analysis-workflow/).
</textarea>
<style data-target="print-only">@media screen {.remark-slide-container{display:block;}.remark-slide-scaler{box-shadow:none;}}</style>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script>
<script src="assets/remark-zoom.js"></script>
<script src="https://platform.twitter.com/widgets.js"></script>
<script>var slideshow = remark.create({
"highlightStyle": "github",
"highlightLines": true,
"countIncrementalSlides": false,
"ratio": "16:9",
"navigation": {
"scroll": false
}
});
if (window.HTMLWidgets) slideshow.on('afterShowSlide', function (slide) {
window.dispatchEvent(new Event('resize'));
});
(function(d) {
var s = d.createElement("style"), r = d.querySelector(".remark-slide-scaler");
if (!r) return;
s.type = "text/css"; s.innerHTML = "@page {size: " + r.style.width + " " + r.style.height +"; }";
d.head.appendChild(s);
})(document);
(function(d) {
var el = d.getElementsByClassName("remark-slides-area");
if (!el) return;
var slide, slides = slideshow.getSlides(), els = el[0].children;
for (var i = 1; i < slides.length; i++) {
slide = slides[i];
if (slide.properties.continued === "true" || slide.properties.count === "false") {
els[i - 1].className += ' has-continuation';
}
}
var s = d.createElement("style");
s.type = "text/css"; s.innerHTML = "@media print { .has-continuation { display: none; } }";
d.head.appendChild(s);
})(document);
// delete the temporary CSS (for displaying all slides initially) when the user
// starts to view slides
(function() {
var deleted = false;
slideshow.on('beforeShowSlide', function(slide) {
if (deleted) return;
var sheets = document.styleSheets, node;
for (var i = 0; i < sheets.length; i++) {
node = sheets[i].ownerNode;
if (node.dataset["target"] !== "print-only") continue;
node.parentNode.removeChild(node);
}
deleted = true;
});
})();
(function() {
"use strict"
// Replace <script> tags in slides area to make them executable
var scripts = document.querySelectorAll(
'.remark-slides-area .remark-slide-container script'
);
if (!scripts.length) return;
for (var i = 0; i < scripts.length; i++) {
var s = document.createElement('script');
var code = document.createTextNode(scripts[i].textContent);
s.appendChild(code);
var scriptAttrs = scripts[i].attributes;
for (var j = 0; j < scriptAttrs.length; j++) {
s.setAttribute(scriptAttrs[j].name, scriptAttrs[j].value);
}
scripts[i].parentElement.replaceChild(s, scripts[i]);
}
})();
(function() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
links[i].target = '_blank';
}
}
})();
// adds .remark-code-has-line-highlighted class to <pre> parent elements
// of code chunks containing highlighted lines with class .remark-code-line-highlighted
(function(d) {
const hlines = d.querySelectorAll('.remark-code-line-highlighted');
const preParents = [];
const findPreParent = function(line, p = 0) {
if (p > 1) return null; // traverse up no further than grandparent
const el = line.parentElement;
return el.tagName === "PRE" ? el : findPreParent(el, ++p);
};
for (let line of hlines) {
let pre = findPreParent(line);
if (pre && !preParents.includes(pre)) preParents.push(pre);
}
preParents.forEach(p => p.classList.add("remark-code-has-line-highlighted"));
})(document);</script>
<script>
slideshow._releaseMath = function(el) {
var i, text, code, codes = el.getElementsByTagName('code');
for (i = 0; i < codes.length;) {
code = codes[i];
if (code.parentNode.tagName !== 'PRE' && code.childElementCount === 0) {
text = code.textContent;
if (/^\\\((.|\s)+\\\)$/.test(text) || /^\\\[(.|\s)+\\\]$/.test(text) ||
/^\$\$(.|\s)+\$\$$/.test(text) ||
/^\\begin\{([^}]+)\}(.|\s)+\\end\{[^}]+\}$/.test(text)) {
code.outerHTML = code.innerHTML; // remove <code></code>
continue;
}
}
i++;
}
};
slideshow._releaseMath(document);
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-MML-AM_CHTML';
if (location.protocol !== 'file:' && /^https?:/.test(script.src))
script.src = script.src.replace(/^https?:/, '');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
</body>
</html>