-
Notifications
You must be signed in to change notification settings - Fork 221
/
eda_tidygraph.Rmd
483 lines (267 loc) · 9.23 KB
/
eda_tidygraph.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
478
479
480
481
482
483
# 社会网络分析 {#eda-tidygraph}
```{r, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
warning = FALSE,
message = FALSE,
fig.showtext = TRUE
)
```
本章通过tidygraph宏包介绍社会网络分析。社会网络分析涉及的知识比较多,而tidygraph将网络结构规整地比较清晰,降低了学习难度,很适合入门学习。
```{r tidygraph-1, message = FALSE, warning = FALSE}
library(tidyverse)
library(tidygraph)
library(ggraph)
```
## 图论基本知识
网络图有两个主要特征: `nodes` and `edges`,
- **nodes**:
- **edges**:
```{r tidygraph-2, out.width = '70%', fig.align='center', echo = FALSE}
knitr::include_graphics("images/node_edge01.png")
```
当然还包括其它的概念,比如
- **adjacency matrix**:
- **edge list**:
- **Node list**:
- **Weighted network graph**:
- **Directed and undirected network graph**:
有向图
```{r tidygraph-3, out.width = '70%', fig.align='center', echo = FALSE}
knitr::include_graphics("images/node_edge02.png")
```
无向图
```{r tidygraph-4, out.width = '70%', fig.align='center', echo = FALSE}
knitr::include_graphics("images/node_edge03.png")
```
## 网络分析
先介绍tidygraph宏包
### tidygraph: A tidy API for graph manipulation
```{r tidygraph-5, out.width = '70%', fig.align='center', echo = FALSE}
knitr::include_graphics("images/workflow_c.png")
```
### Tidy Network Anaylsis
- 在 `tidygraph` 框架, 网络数据可以分解成两个tidy数据框:
- 一个是 **node** data
- 一个是 **edge** data
- `tidygraph` 宏包提供了**node**数据框和**edge**数据框相互切换的方案,并且可以使用**dplyr**的语法操控
- `tidygraph` 提供了常用的网络结构的**algorithms**,比如,计算网络拓扑结构中节点的重要性、中心度等。
### Create network objects
创建网络对象主要有两个函数:
- `tbl_graph()`. Creates a network object from nodes and edges data
- `as_tbl_graph()`. Converts network data and objects to a `tbl_graph` network.
案例: 欧盟总统之间通话以及次数。
```{r tidygraph-6}
library("navdata") # devtools::install_github("kassambara/navdata")
data("phone.call2")
```
```{r tidygraph-7}
node_list <- phone.call2$nodes
node_list
```
```{r tidygraph-8}
edge_list <- phone.call2$edges
edge_list
```
### Use `tbl_graph`
- Create a `tbl_graph` network object using the phone call data:
```{r tibble to tbl_graph}
phone.net <- tbl_graph(nodes = node_list, edges = edge_list, directed = TRUE)
```
- Visualize the network graph
```{r tidygraph-9, out.width = '50%', fig.align='center'}
ggraph(phone.net, layout = "graphopt") +
geom_edge_link(width = 1, colour = "lightgray") +
geom_node_point(size = 4, colour = "red") +
geom_node_text(aes(label = label), repel = TRUE) +
theme_graph()
```
### Use `as_tbl_graph`
mtcars data set: R 的内置数据集,记录了32种不同品牌的轿车的的11个属性
1、we create a correlation matrix network graph
```{r tidygraph-10, eval=FALSE}
library(corrr)
res.cor <- datasets::mtcars[, c(1, 3:6)] %>% # (1)
t() %>%
corrr::correlate() %>% # (2)
corrr::shave(upper = TRUE) %>% # (3)
corrr::stretch(na.rm = TRUE) %>% # (4)
dplyr::filter(r >= 0.998) # (5)
res.cor
```
2、Create the correlation network graph:
```{r tidygraph-11, eval=FALSE}
set.seed(1)
cor.graph <- as_tbl_graph(res.cor, directed = FALSE)
```
```{r tidygraph-12, out.width = '50%', fig.align='center', eval=FALSE}
ggraph(cor.graph) +
geom_edge_link() +
geom_node_point() +
geom_node_text(
aes(label = name),
size = 3, repel = TRUE
) +
theme_graph()
```
### Print out a network object
```{r tidygraph-13, eval=FALSE}
cor.graph
```
### extract the current active data
```{r tidygraph-14, eval=FALSE}
cor.graph %>%
activate(edges) %>%
arrange(desc(r))
```
Note that, to extract the current active data as a tibble, you can use the function `as_tibble(cor.graph)`.
## Network graph manipulation
### Car groups info (Number of cylinders)
```{r tidygraph-15, eval=FALSE}
# Car groups info
cars.group <- tibble(
name = rownames(datasets::mtcars),
cyl = as.factor(datasets::mtcars$cyl)
)
cars.group
```
### Modify the nodes data:
```{r tidygraph-16, eval=FALSE}
# Modify the nodes data
cor.graph <- cor.graph %>%
activate(nodes) %>%
left_join(cars.group, by = "name") %>%
rename(label = name)
cor.graph
```
### Modify the edge data.
```{r tidygraph-17, eval=FALSE}
# Modify the edge data.
cor.graph <- cor.graph %>%
activate(edges) %>%
rename(weight = r)
cor.graph
```
### Display the final modified graphs object:
```{r tidygraph-18, eval=FALSE}
cor.graph
```
### Visualize the correlation network
```{r tidygraph-19, message=FALSE, warning=FALSE, out.width='50%', eval=FALSE}
set.seed(1)
ggraph(cor.graph) +
geom_edge_link(aes(width = weight), alpha = 0.2) +
scale_edge_width(range = c(0.2, 1)) +
geom_node_point(aes(color = cyl), size = 2) +
geom_node_text(aes(label = label), size = 3, repel = TRUE) +
theme_graph()
```
## Network analysis
### Centrality
Centrality is an important concept when analyzing network graph.
The `tidygraph` package contains more than 10 centrality measures, prefixed with the term `centrality_` :
```{r tidygraph-20, echo=TRUE}
# centrality_alpha()
# centrality_power()
# centrality_authority()
# centrality_betweenness()
# centrality_closeness()
# centrality_hub()
# centrality_degree()
# centrality_pagerank()
# centrality_eigen()
# centrality_subgraph
# centrality_edge_betweenness()
```
example:
- use the phone call network graph ( 欧盟总统之间通话以及次数)
- compute nodes centrality
```{r tidygraph-21, eval=FALSE}
set.seed(123)
phone.net %>%
activate(nodes) %>%
mutate(centrality = centrality_authority())
```
```{r tidygraph-22, message=FALSE, warning=FALSE, out.width='90%', eval=FALSE}
set.seed(123)
phone.net %>%
activate(nodes) %>%
mutate(centrality = centrality_authority()) %>%
ggraph(layout = "graphopt") +
geom_edge_link(width = 1, colour = "lightgray") +
geom_node_point(aes(size = centrality, colour = centrality)) +
geom_node_text(aes(label = label), repel = TRUE) +
scale_color_gradient(low = "yellow", high = "red") +
theme_graph()
```
### Clustering
- Clustering is a common operation in network analysis and it consists of grouping nodes based on the graph topology.
- Many clustering algorithms from are available in the tidygraph package and prefixed with the term group_. These include:
- **Infomap community finding**. It groups nodes by minimizing the expected description length of a random walker trajectory. R function: `group_infomap()`
- **Community structure detection based on edge betweenness**. It groups densely connected nodes. R function: `group_edge_betweenness()`
example:
- use the correlation network graphs (记录了32种不同品牌的轿车的的11个属性)
- detect clusters or communities
```{r tidygraph-23, eval=FALSE}
set.seed(123)
cluster_mtcars <- cor.graph %>%
activate(nodes) %>%
mutate(community = as.factor(group_infomap()))
cluster_mtcars
```
```{r tidygraph-24, message=FALSE, warning=FALSE, out.width='90%', eval=FALSE}
cluster_mtcars %>%
ggraph(layout = "graphopt") +
geom_edge_link(width = 1, colour = "lightgray") +
geom_node_point(aes(colour = community), size = 4) +
geom_node_text(aes(label = label), repel = TRUE) +
theme_graph()
```
### More Algorithms
```{r tidygraph-25, out.width = '90%', fig.align='center', echo = FALSE}
knitr::include_graphics("images/Algorithms.png")
```
## 小结
```{r tidygraph-26, out.width = '70%', fig.align='center', echo = FALSE}
knitr::include_graphics("images/tbl_graph02.png")
```
tidybayes很聪明地将复杂的网络结构用两个数据框表征出来,node 数据框负责**节点**的属性,edge 数据框负责**网络连接**的属性,调整其中的一个数据框,另一个也会相应的调整,比如node数据框中删除一个节点,edge数据框就会自动地删除该节点的所有连接。
```{r tidygraph-27, out.width = '70%', fig.align='center', echo = FALSE}
knitr::include_graphics("images/tbl_graph04.png")
```
## Network Visualization
这里主要介绍tidygraph配套的[ggraph](https://github.com/thomasp85/ggraph)宏包,它们的作者都是同一个人。
### ggraph: A grammar of graphics for relational data
ggraph 沿袭了ggplot2的语法规则,
```{r tidygraph-28, message=FALSE, warning=FALSE, eval=FALSE}
cluster_mtcars %>%
# Layout
ggraph(layout = "graphopt") +
# Edges
geom_edge_link(
width = 1,
colour = "lightgray"
) +
# Nodes
geom_node_point(
aes(colour = community),
size = 4
) +
geom_node_text(
aes(label = label),
repel = TRUE
) +
theme_graph()
```
## 扩展阅读
- <https://www.data-imaginist.com/2017/introducing-tidygraph/>
- <https://github.com/thomasp85/tidygraph>
- <https://christophergandrud.github.io/networkD3/>
```{r tidygraph-29, echo = F}
# remove the objects
# rm(list=ls())
#rm(cars.group, cluster_mtcars, cor.graph, edge_list, node_list, phone.call2, phone.net, res.cor)
```
```{r tidygraph-30, echo = F, message = F, warning = F, results = "hide"}
pacman::p_unload(pacman::p_loaded(), character.only = TRUE)
```