-
Notifications
You must be signed in to change notification settings - Fork 11
/
07-Networks.Rmd
477 lines (321 loc) · 14.1 KB
/
07-Networks.Rmd
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
# Networks
**Learning Objectives**
- What is Network data?
- New functions and geoms
- Visualization of nodes and edges as abstract concepts
## Introduction
This chapter illustrates how to make a Network of data, and how to make practical examples using some of the available packages:
- `{tidygraph}` for Tidy API for Graph Manipulation
- `{ggraph}` for network visualization
- `{igraph}` for generating random and regular graphs
## What is network data?
Networks data consists of entities (nodes or vertices) and their relation (edges or links).
Edges can be: directed or undirected
### A tidy network manipulation API
The first package is `tidygraph()` a dplyr API for network data.
New functions:
- `activate()` informs tidygraph on which part of the network you want to work on, either nodes or edges.
- `.N()` which gives access to the node data of the current graph even when working with the edges
- `.E()` and `.G()` to access the edges or the whole graph)
```{r 07-01, message=FALSE, warning=FALSE, include=FALSE, paged.print=FALSE}
library(tidyverse)
```
In this **example** we create a graph, assign a random label to the nodes, and sort the edges based on the label of their source node.
The function `play_erdos_renyi()` creates graphs directly through sampling of different attributes.
```{r 07-play_erdos_renyi, message=FALSE, warning=FALSE, paged.print=FALSE}
library(tidygraph)
graph <- tidygraph::play_erdos_renyi(n = 10, p = 0.2) %>%
activate(nodes) %>%
mutate(class = sample(letters[1:4], n(), replace = TRUE)) %>%
activate(edges) %>%
arrange(.N()$class[from])
graph
```
### Conversion
Data can be converted with `as_tbl_graph()`, a data structure for tidy graph manipulation. It converts a data frame encoded as an edgelist, as well as converting the result of `hclust()`
```{r 07-highschool}
data(highschool, package = "ggraph")
head(highschool)
```
With `as_tbl_graph()` we obtain:
```{r 07-hs_graph}
hs_graph <- tidygraph::as_tbl_graph(highschool, directed = FALSE)
hs_graph
```
#### hclust() and dist() functions:
In this **example** the `luv_colours()` function allows for all built-in `colors()` translated into **Luv colour space**, a data frame with 657 observations and 4 variables:
[luv_colours](https://github.com/tidyverse/ggplot2/blob/main/data-raw/luv_colours.R)
```{r 07-luv_colours}
luv_colours <- as.data.frame(convertColor(t(col2rgb(colors())),
"sRGB", "Luv"))
luv_colours$col <- colors()
head(luv_colours)
```
This visualization represent the content of the dataset, then we will see how it looks in a grapg representation.
```{r 07-colors}
ggplot(luv_colours, aes(u, v)) +
geom_point(aes(colour = col), size = 3) +
scale_color_identity() +
coord_equal() +
theme_void()
```
For example, selecting the first 3 variables and plotting the data with the plot() function we can see that there are some connections within the elements of the dataset, as the colors are connected to each other.
```{r 07-palette}
ggplot2::luv_colours[, 1:3] %>% head
plot(ggplot2::luv_colours[, 1:3])
```
```{r 07-hclust}
luv_clust <- hclust(dist(ggplot2::luv_colours[, 1:3]))
```
```{r 07-class}
class(luv_clust)
```
With the `tidygraph::as_tbl_graph()` function we can transorm the dataset into classes "tbl_graph", "igraph" to make it ready to use for making a visualization of the network data.
```{r 07-luv_graph}
luv_graph <- as_tbl_graph(luv_clust)
luv_graph;class(luv_graph)
```
### Algorithms
The real benefit of networks comes from the different operations that can be performed on them using the underlying structure.
```{r 07-luv_graph2}
luv_graph %>%
tidygraph::activate(nodes) %>%
mutate(centrality = centrality_pagerank()) %>%
arrange(desc(centrality))
```
## Visualizing networks
To visualize the **Network data** we use **{ggraph}**.
It builds on top of {tidygraph} and {ggplot2} to allow a complete and familiar grammar of graphics for network data.
### Setting up the visualization
Syntax of **{ggraph}**:
ggraph() %>%
ggraph::geom_<functions>
it will choose an appropriate layout based on the type of graph you provide.
[Getting Started guide to layouts](https://ggraph.data-imaginist.com/articles/Layouts.html)
#### Specifying a layout
What is the base requirenment?
The data frame need to be with at least an x and y column and with the same number of rows as there are nodes in the input graph.
As an **example** we take the `data(highschool, package = "ggraph")` and make a **visualization** of the graph:
hs_graph <- tidygraph::as_tbl_graph(highschool,
directed = FALSE)
```{r 07-02, message=FALSE, warning=FALSE, paged.print=FALSE}
library(ggraph)
ggraph(hs_graph) +
geom_edge_link() +
geom_node_point()
```
A second **example** is with more features:
```{r 07-03}
hs_graph <- hs_graph %>%
tidygraph::activate(edges) %>%
mutate(edge_weights = runif(n()))
ggraph(hs_graph, layout = "stress", weights = edge_weights) +
geom_edge_link(aes(alpha = edge_weights)) +
geom_node_point() +
scale_edge_alpha_identity()
```
In the following **examples** we see different [layouts](https://www.data-imaginist.com/2017/ggraph-introduction-layouts/).
Information about "drl" type of layout: DRL force-directed graph layout, an be found in the [igraph](https://igraph.org/r/doc/layout_with_drl.html) package.
```{r 07-03b}
layout <- ggraph::create_layout(hs_graph, layout = 'drl')
ggraph(layout) +
geom_edge_link() +
geom_node_point()
```
Instead of {tidygraph} we use {igraph}, with layout = "kk": layout.kamada.kawai
```{r 07-04, message=FALSE, warning=FALSE, paged.print=FALSE}
require(ggraph)
require(igraph)
hs_graph2 <- igraph::graph_from_data_frame(highschool)
layout <- create_layout(hs_graph2, layout = "kk")
ggraph(layout) +
geom_edge_link(aes(colour = factor(year))) +
geom_node_point()
```
A very simple example to understand how to make a graph network is from this tutorial: [Networks in igraph](https://kateto.net/netscix2016.html)
To understand a bit more about the graph structure we can use these functions:
```{r 07-04b}
g1 <- igraph::graph( edges=c(1,2, 2,3, 3, 1), n=3, directed=F )
E(g1); # access to the edges
V(g1); # the vertics
g1[] # access to the matrix
```
#### Circularity
Layouts can be **linear** and **circular**.
coord_polar() changes the coordinate system and not affect the edges
```{r 07-05}
ggraph(luv_graph, layout = 'dendrogram', circular = TRUE) +
geom_edge_link() +
coord_fixed()
```
```{r 07-06}
ggraph(luv_graph, layout = 'dendrogram') +
geom_edge_link() +
coord_polar() +
scale_y_reverse()
```
### Drawing nodes
- points
- more specialized geoms: tiles
geom_node_<functions>
geom_node_point()
geom_node_tile()
[Getting Started guide to nodes](https://ggraph.data-imaginist.com/articles/Nodes.html)
```{r 07-luv_graph_tree}
ggraph(luv_graph, layout = "stress") +
geom_edge_link() +
geom_node_point(aes(colour =factor(members)),
show.legend = F)
```
More features could be added to calculate node and edge centrality, such as:
- centrality_power()
- centrality_degree()
```{r 07-07}
ggraph(luv_graph, layout = "stress") +
geom_edge_link() +
geom_node_point(aes(colour =centrality_power()))
```
Or making tiles:
```{r 07-08, message=FALSE, warning=FALSE, paged.print=FALSE}
ggraph(luv_graph, layout = "treemap") +
geom_node_tile(aes(fill = depth))
```
### Drawing edges
`geom_edge_link()` draws a straight line between the connected nodes, actually what it does is: it will split up the line in a bunch of small fragments.
- geom_edge_link()
- geom_edge_link2()
- geom_edge_fan()
- geom_edge_parallel()
- geom_edge_elbow()
- geom_edge_bend()
- geom_edge_diagonal()
[Getting Started guide to edges](https://ggraph.data-imaginist.com/articles/Edges.html)
The `after_stat(index)`:
```{r 07-09}
set.seed(123)
ggraph(hs_graph, layout = "stress") +
geom_edge_link(aes(alpha = after_stat(index)))
```
Here is an example about how to use `node.class variable`, the graph is the first that we have seen and it is artificially made with:
tidygraph::play_erdos_renyi()
```{r 07-10}
graph <- tidygraph::play_erdos_renyi(n = 10, p = 0.2) %>%
activate(nodes) %>%
mutate(class = sample(letters[1:4],
n(), replace = TRUE)) %>%
activate(edges) %>%
arrange(.N()$class[from])
ggraph(graph, layout = "stress") +
geom_edge_link2(
aes(colour = node.class),
width = 3,
lineend = "round")
```
```{r 07-11}
ggraph(hs_graph, layout = "stress") +
geom_edge_parallel()
```
Trees and specifically **dendrograms**:
```{r 07-12}
ggraph(luv_graph, layout = "dendrogram", height = height) +
geom_edge_elbow()
```
#### Clipping edges around the nodes
Example: using arrows to show directionality of edges
```{r 07-13}
set.seed(1011)
ggraph(graph, layout = "stress") +
geom_edge_link(
arrow = arrow(),
start_cap = circle(5, "mm"),
end_cap = circle(5, "mm")
) +
geom_node_point(aes(colour = class), size = 8)
```
#### An edge is not always a line
Nodes and edges are abstract concepts and can be visualized in a multitude of ways.
- geom_edge_point()
```{r 07-14}
ggraph(hs_graph, layout = "matrix", sort.by = node_rank_traveller()) +
geom_edge_point()
```
### Faceting
- facet_nodes()
- facet_edges()
- facet_graph()
```{r 07-15}
ggraph(hs_graph, layout = "stress") +
geom_edge_link() +
geom_node_point() +
facet_edges(~year)
```
## Conclusions
Making a **{ggraph}** means understanding of the different classes of datasets that can be used inside the function. Also, very important is to have clear in mind the structure of the graph that you would like to acheive for representing your data.
There are many layouts available, and they differ by the class of provided data.
In addition, to do not forget that you can make a network of data using **{ggplot2}** as well.
### Resources:
- [tidygraph website](https://tidygraph.data-imaginist.com)
- [Data Imaginist](https://ggraph.data-imaginist.com)
- [Imaginist layouts](https://www.data-imaginist.com/2017/ggraph-introduction-layouts/)
- [Network analysis with r](https://www.jessesadler.com/post/network-analysis-with-r/)
- [R and igraph](https://igraph.org/r/)
- [Getting Started guide to layouts](https://ggraph.data-imaginist.com/articles/Layouts.html)
- [Getting Started guide to nodes](https://ggraph.data-imaginist.com/articles/Nodes.html)
- [Getting Started guide to edges](https://ggraph.data-imaginist.com/articles/Edges.html)
## Meeting Videos
### Cohort 1
`r knitr::include_url("https://www.youtube.com/embed/RiACZPhm53Y")`
<details>
<summary> Meeting chat log </summary>
```
00:09:20 priyanka gagneja: sorry everyone I just joined
00:09:38 Federica Gazzelloni: Hello!
00:10:02 priyanka gagneja: and will probably be a little in and out .. got a not so happy baby today at home
00:18:11 Stan Piotrowski: I need to take off for a conflict that just came up. Catch up with you all on slack!
00:20:46 SriRam: It is the image product ID
00:21:07 SriRam: All the IDE’s
00:21:50 Kent Johnson: The IDE codes are defined here: https://ropensci.github.io/bomrang/reference/get_available_imagery.html
00:27:32 SriRam: The process is called geo-referencing
00:27:58 SriRam: And image is called a geo-referenced image
00:31:33 SriRam: Yes, it is a reference system
00:31:38 SriRam: A coordinate reference
00:33:04 Federica Gazzelloni: this is the bit that makes the reference: crs = st_crs(sat_vis)
00:49:27 Jiwan Heo: something just came up, and have to leave. See you all next week!
00:59:58 priyanka gagneja: I am signing off now , can someone please address and sign off on my behalf. I will send a msg later on slack
```
</details>
`r knitr::include_url("https://www.youtube.com/embed/SV-fN7qYPso")`
<details>
<summary> Meeting chat log </summary>
```
00:15:36 Ryan S: https://www.youtube.com/playlist?list=PLkrJrLs7xfbWjD2rp3pIV85lby-tR3Cnu
00:15:48 Lydia Gibson: Thanks Ryan!
00:16:00 Ryan S: link to a very good basic tutorial on simple features
00:53:58 Lydia Gibson: What is GPU?
00:54:23 Ryan S: GPU is the graphics processing unit (I think)
00:54:31 Lydia Gibson: Thank you
00:54:32 Ryan S: it's the part that "draws" on your screen
00:54:43 Lydia Gibson: Oh okay
00:54:56 Ryan S: versus the CPU that does calculations
00:55:48 SriRam: For 2D and non texture plots, I think it is more a RAM issue
00:55:59 Ryan Metcalf: Oh. I’m so sorry for using Acronyms! Ryan S. is correct. The balance I’m asking Federica is related….”Can I use a slow Laptop or do I have to use a super computer with massive Video card to render these types of graphical objects.
00:56:23 Lydia Gibson: I always thought CPU was synonymous with computer.
00:57:22 Ryan S: Ryan, just repurpose the GPUs you currently have that are mining crypto
00:57:38 Ryan Metcalf: :) Agreed!!!
00:57:57 SriRam: Lol
00:59:14 SriRam: If you have a spatial network, do not miss out on “sfnetworks” package
01:00:07 Federica Gazzelloni: https://kateto.net/netscix2016.html
01:00:14 Federica Gazzelloni: https://www.data-imaginist.com/2017/ggraph-introduction-layouts/
01:00:24 Federica Gazzelloni: https://www.hcbravo.org/networks-across-scales/misc/tidygraph.nb.html
01:00:41 Federica Gazzelloni: https://igraph.org/r/doc/layout_with_drl.html
01:00:48 Federica Gazzelloni: https://tidygraph.data-imaginist.com/reference/index.html#section-misc
01:00:57 Federica Gazzelloni: https://ggraph.data-imaginist.com/articles/Layouts.html
01:01:52 Federica Gazzelloni: https://web.stanford.edu/class/bios221/book/Chap-Graphs.html
https://github.com/jtichon/ModernStatsModernBioJGT/tree/master/data
https://simplemaps.com/data/world-cities
01:07:00 SriRam: Tidy is I think , Hadley definition, variable is a column, sample point is a row
01:07:36 SriRam: Sorry my microphone does not work since a few sessions now 🙁
01:07:50 Ryan S: borders on "marketing" to some degree. :)
01:08:08 SriRam: Sfnetwork is not for graphs, it is more for spatial operations
```
</details>