-
Notifications
You must be signed in to change notification settings - Fork 151
/
Sunbelt 2021 R Network Visualization Workshop.R
1495 lines (1026 loc) · 52.4 KB
/
Sunbelt 2021 R Network Visualization Workshop.R
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
992
993
994
995
996
997
998
999
1000
##========================================================##
## ##
## Network Visualization with R ##
## Sunbelt 2021 Workshop ##
## www.kateto.net/sunbelt2021 ##
## ##
## Katherine (Katya) Ognyanova ##
## Web: kateto.net | Email: [email protected] ##
## GitHub: kateto | Twitter: @Ognyanova ##
## ##
##========================================================##
# ================ Introduction ================
# Download the workshop materials: bit.ly/sunbelt-2021
# Online tutorial: kateto.net/sunbelt2021
# CONTENTS
#
# 1. Working with colors in R plots
# 2. Reading in the network data
# 3. Network plots in 'igraph'
# 4. Plotting two-mode networks
# 5. Plotting multiplex networks
# 6. Beyond igraph: Statnet & ggraph
# 7. Simple plot animations in R
# 8. Interactive JavaScript networks
# 9. Interactive and dynamic networks with ndtv-d3
# 10. Plotting networks on a geographic map
# KEY PACKAGES
# Install those now if you do not have the latest versions.
# (please do NOT load them yet!)
# install.packages("igraph")
# install.packages("network")
# install.packages("sna")
# install.packages("visNetwork")
# install.packages("threejs")
# install.packages("ndtv")
# OPTIONAL PACKAGES
# Install those if you would like to run through all of the
# examples below (those are not critical and can be skipped).
# install.packages("png")
# install.packages("ggraph")
# install.packages("networkD3")
# install.packages("animation")
# install.packages("maps")
# install.packages("geosphere")
# ================ 1. Colors in R plots ================
# -------~~ Colors --------
# In most R functions, you can use named colors, hex, or rgb values:
plot(x=1:10, y=rep(5,10), pch=19, cex=5, col="dark red")
points(x=1:10, y=rep(6, 10), pch=19, cex=5, col="#557799")
points(x=1:10, y=rep(4, 10), pch=19, cex=5, col=rgb(.25, .5, .3))
# In the simple base plot chart above, x and y are point coordinates, 'pch'
# is the point symbol shape, 'cex' is the point size, and 'col' is the color.
# to see the parameters for plotting in base R, check out ?par
# If you plan on using the built-in color names, here's what they are:
colors() # all colors
grep("blue", colors(), value=T) # colors that have 'blue' in the name
# You may notice that rgb here ranges from 0 to 1. While this is the R default,
# you can also set it for the more typical 0-255 range:
rgb(10, 100, 100, maxColorValue=255)
# -------~~ Transparency --------
# We can also set the opacity/transparency using the parameter 'alpha' (range 0-1):
plot(x=1:5, y=rep(5,5), pch=19, cex=16, col=rgb(.25, .5, .3, alpha=.5), xlim=c(0,6))
# If we have a hex color representation, we can set the transparency alpha
# using 'adjustcolor' from package 'grDevices'. For fun, let's also set the
# the plot background to black using the par() function for graphical parameters.
# We could also set the margins in par() with mar=c(bottom, left, top, right).
par(bg="black")
col.tr <- grDevices::adjustcolor("#557799", alpha=0.7)
plot(x=1:5, y=rep(5,5), pch=19, cex=20, col=col.tr, xlim=c(0,6))
dev.off() # shut off the graphic device and clears the current configuration.
# -------~~ Palettes --------
# In many cases, we need a number of contrasting colors, or multiple shades of a color.
# R comes with some predefined palette function that can generate those for us.
pal1 <- heat.colors(5, alpha=1) # generate 5 colors from the heat palette, opaque
pal2 <- rainbow(5, alpha=.5) # generate 5 colors from the heat palette, semi-transparent
plot(x=1:10, y=1:10, pch=19, cex=10, col=pal1)
par(new=TRUE) # tells R not to clear the first plot before adding the second one
plot(x=10:1, y=1:10, pch=19, cex=10, col=pal2)
# We can also generate our own gradients using colorRampPalette().
# Note that colorRampPalette returns a *function* that we can use
# to generate as many colors from that palette as we need.
palf <- colorRampPalette(c("gray70", "dark red"))
plot(x=10:1, y=1:10, pch=19, cex=10, col=palf(10))
# To add transparency to colorRampPalette, you need to add a parameter `alpha=TRUE`:
palf <- colorRampPalette(c(rgb(1,1,1, .2),rgb(.8,0,0, .7)), alpha=TRUE)
plot(x=10:1, y=1:10, pch=19, cex=10, col=palf(10))
# ================ 2. Reading network data into 'igraph' ================
# Download an archive with the data files from http://bit.ly/sunbelt-2021
# Clear your workspace by removing all objects returned by ls():
rm(list = ls())
# Load the 'igraph' library:
library("igraph")
# -------~~ DATASET 1: edgelist --------
# Read in the data:
nodes <- read.csv("https://kateto.net/workshops/data/Dataset1-Media-Example-NODES.csv", header=T, as.is=T)
links <- read.csv("https://kateto.net/workshops/data/Dataset1-Media-Example-EDGES.csv", header=T, as.is=T)
# Examine the data:
head(nodes)
head(links)
# Converting the data to an igraph object:
# The graph_from_data_frame() function takes two data frames: 'd' and 'vertices'.
# 'd' describes the edges of the network - it should start with two columns
# containing the source and target node IDs for each network tie.
# 'vertices' should start with a column of node IDs.
# Any additional columns in either data frame are interpreted as attributes.
net <- graph_from_data_frame(d=links, vertices=nodes, directed=T)
# Examine the resulting object:
class(net)
net
# We can access the nodes, edges, and their attributes:
E(net)
V(net)
E(net)$type
V(net)$media
# Or find specific nodes and edges by attribute:
# (that returns objects of type vertex sequence / edge sequence)
V(net)[media=="BBC"]
E(net)[type=="mention"]
# If you need them, you can extract an edge list
# or a matrix back from the igraph networks.
as_edgelist(net, names=T)
as_adjacency_matrix(net, attr="weight")
# Or data frames describing nodes and edges:
as_data_frame(net, what="edges")
as_data_frame(net, what="vertices")
# You can also look at the network matrix directly:
net[1,]
net[5,7]
# First attempt to plot the graph:
plot(net) # not pretty!
# Removing loops from the graph:
net <- simplify(net, remove.multiple = F, remove.loops = T)
# Let's and reduce the arrow size and remove the labels:
plot(net, edge.arrow.size=.4,vertex.label=NA)
# -------~~ DATASET 2: matrix --------
# Read in the data:
nodes2 <- read.csv("https://kateto.net/workshops/data/Dataset2-Media-User-Example-NODES.csv", header=T, as.is=T)
links2 <- read.csv("https://kateto.net/workshops/data/Dataset2-Media-User-Example-EDGES.csv", header=T, row.names=1)
# Examine the data:
head(nodes2)
head(links2)
# links2 is a matrix for a two-mode network:
links2 <- as.matrix(links2)
dim(links2)
dim(nodes2)
# Create an igraph network object from the two-mode matrix:
net2 <- graph_from_incidence_matrix(links2)
# A built-in vertex attribute 'type' shows which mode vertices belong to.
table(V(net2)$type)
plot(net2,vertex.label=NA)
# Examine the resulting object:
class(net2)
net2
# To transform a one-mode network matrix into an igraph object,
# we would use graph_from_adjacency_matrix()
# ================ 3. Network plots in 'igraph' ================
# ------~~ Plot parameters in igraph --------
# Check out the node options (starting with 'vertex.')
# and the edge options # (starting with 'edge.').
# A list of options is also included in your handout.
?igraph.plotting
# We can set the node & edge options in two ways - one is to specify
# them in the plot() function, as we are doing below.
# Plot with curved edges (edge.curved=.1) and reduce arrow size:
plot(net, edge.arrow.size=.4, edge.curved=.1)
# Set node color to orange and the border color to hex #555555
# Replace the vertex label with the node names stored in "media"
plot(net, edge.arrow.size=.2, edge.curved=0,
vertex.color="orange", vertex.frame.color="#555555",
vertex.label=V(net)$media, vertex.label.color="black",
vertex.label.cex=.7)
# The second way to set attributes is to add them to the igraph object.
# Generate colors based on media type:
colrs <- c("gray50", "tomato", "gold")
V(net)$color <- colrs[V(net)$media.type]
# Compute node degrees (#links) and use that to set node size:
deg <- degree(net, mode="all")
V(net)$size <- deg*3
# Alternatively, we can set node size based on audience size:
V(net)$size <- V(net)$audience.size*0.7
# The labels are currently node IDs.
# Setting them to NA will render no labels:
V(net)$label.color <- "black"
V(net)$label <- NA
# Set edge width based on weight:
E(net)$width <- E(net)$weight/6
#change arrow size and edge color:
E(net)$arrow.size <- .2
E(net)$edge.color <- "gray80"
# We can even set the network layout:
graph_attr(net, "layout") <- layout_with_lgl
plot(net)
# We can also override the attributes explicitly in the plot:
plot(net, edge.color="orange", vertex.color="gray50")
# We can also add a legend explaining the meaning of the colors we used:
plot(net)
legend(x=-1.1, y=-1.1, c("Newspaper","Television", "Online News"), pch=21,
col="#777777", pt.bg=colrs, pt.cex=2.5, bty="n", ncol=1)
# Sometimes, especially with semantic networks, we may be interested in
# plotting only the labels of the nodes:
plot(net, vertex.shape="none", vertex.label=V(net)$media,
vertex.label.font=2, vertex.label.color="gray40",
vertex.label.cex=.7, edge.color="gray85")
# Let's color the edges of the graph based on their source node color.
# We'll get the starting node for each edge with "ends()".
edge.start <- ends(net, es=E(net), names=F)[,1]
edge.col <- V(net)$color[edge.start]
plot(net, edge.color=edge.col, edge.curved=.1)
# -------~~ Network Layouts in 'igraph' --------
# Network layouts are algorithms that return coordinates for each
# node in a network.
# Let's generate a slightly larger 100-node graph using
# a preferential attachment model (Barabasi-Albert).
net.bg <- sample_pa(100, 1.2)
V(net.bg)$size <- 8
V(net.bg)$frame.color <- "white"
V(net.bg)$color <- "orange"
V(net.bg)$label <- ""
E(net.bg)$arrow.mode <- 0
plot(net.bg)
# Now let's plot this network using the layouts available in igraph.
# You can set the layout in the plot function:
plot(net.bg, layout=layout_randomly)
# Or calculate the vertex coordinates in advance:
l <- layout_in_circle(net.bg)
plot(net.bg, layout=l)
# l is simply a matrix of x,y coordinates (N x 2) for the N nodes in the graph.
# For 3D layouts, it is matrix of x, y, and z coordinates (N x 3)
# You can generate your own:
l
l <- cbind(1:vcount(net.bg), c(1, vcount(net.bg):2))
plot(net.bg, layout=l)
# This layout is just an example and not very helpful - thankfully
# 'igraph' has a number of built-in layouts, including:
# Randomly placed vertices
l <- layout_randomly(net.bg)
plot(net.bg, layout=l)
# Circle layout
l <- layout_in_circle(net.bg)
plot(net.bg, layout=l)
# 3D sphere layout
l <- layout_on_sphere(net.bg)
plot(net.bg, layout=l)
# Fruchterman-Reingold layout
# Like other force-directed algorithms, it treats graphs as a physical system.
# Nodes are electrically charged particles that repulse each other when they
# get too close. Edges act as springs that pull connected nodes closer.
# F-R is nice but slow, most often used in graphs smaller than ~1000 vertices.
l <- layout_with_fr(net.bg)
plot(net.bg, layout=l)
# With force-directed layouts, you can use the 'niter' parameter to control
# the number of iterations to perform. The default is 500, but you can lower
# it for large graphs to get results faster and check if they look reasonable.
l <- layout_with_fr(net.bg, niter=50)
plot(net.bg, layout=l)
# The layout can also use edge weights. It checks for a 'weight' edge attribute
# in the network object, or you can use a 'weights' parameter in the function.
# Nodes connected by more heavily weighted edges are pulled closer together.
ws <- c(1, rep(100, ecount(net.bg)-1))
lw <- layout_with_fr(net.bg, weights=ws)
plot(net.bg, layout=lw)
# You will also notice that the F-R layout is not deterministic - different
# runs will result in slightly different configurations. Saving the layout
# in l allows us to get the exact same result multiple times.
par(mfrow=c(2,2), mar=c(1,1,1,1))
plot(net.bg, layout=layout_with_fr)
plot(net.bg, layout=layout_with_fr)
plot(net.bg, layout=l)
plot(net.bg, layout=l)
dev.off()
# By default, the coordinates of the plots are rescaled to the [-1,1] interval
# for both x and y. You can change that with the parameter "rescale=FALSE"
# and rescale your plot manually by multiplying the coordinates by a scalar.
# You can use norm_coords to normalize the plot with the boundaries you want.
# This way you can create more compact or spread out layout versions.
# Get the layout coordinates:
l <- layout_with_fr(net.bg)
# Normalize them so that they are in the -1, 1 interval:
l <- norm_coords(l, ymin=-1, ymax=1, xmin=-1, xmax=1)
par(mfrow=c(2,2), mar=c(0,0,0,0))
plot(net.bg, rescale=F, layout=l*0.4)
plot(net.bg, rescale=F, layout=l*0.8)
plot(net.bg, rescale=F, layout=l*1.2)
plot(net.bg, rescale=F, layout=l*1.6)
dev.off()
# Some layouts have 3D versions that you can use with parameter 'dim=3'
l <- layout_with_fr(net.bg, dim=3)
plot(net.bg, layout=l)
# As you might expect, a 3D layout has 3 columns, for X, Y, and Z coordinates:
l
# Another popular force-directed algorithm that produces nice results for
# connected graphs is Kamada Kawai. Like Fruchterman Reingold, it attempts to
# minimize the energy in a spring system.
l <- layout_with_kk(net.bg)
plot(net.bg, layout=l)
# Graphopt is a force-directed layout that uses layering
# to help with visualizations of large networks.
l <- layout_with_graphopt(net.bg)
plot(net.bg, layout=l)
# Graphopt parameters can change the mass and electric charge of nodes
# as well as the optimal spring length and the spring constant for edges.
# The parameter names are 'charge' (default 0.001), 'mass' (default 30),
# 'spring.length' (default 0), and 'spring.constant' (default 1).
# Tweaking those can lead to considerably different graph layouts.
# For instance, the charge parameter below changes node repulsion:
l1 <- layout_with_graphopt(net.bg, charge=0.02)
l2 <- layout_with_graphopt(net.bg, charge=0.00000001)
par(mfrow=c(1,2), mar=c(1,1,1,1))
plot(net.bg, layout=l1)
plot(net.bg, layout=l2)
dev.off()
# The MDS (multidimensional scaling) algorithm tries to place nodes based on some
# measure of similarity or distance between them. More similar nodes are plotted
# closer to each other. By default, the measure used is based on the shortest
# paths between nodes in the network. That can be changed with the 'dist' parameter.
plot(net.bg, layout=layout_with_mds)
# The LGL algorithm is for large connected graphs. Here you can specify a root -
# the node that will be placed in the middle of the layout.
plot(net.bg, layout=layout_with_lgl)
# By default, igraph uses a layout called 'layout_nicely' which selects
# an appropriate layout algorithm based on the properties of the graph.
# Check out all available layouts in igraph:
?igraph::layout_
layouts <- grep("^layout_", ls("package:igraph"), value=TRUE)[-1]
# Remove layouts that do not apply to our graph.
layouts <- layouts[!grepl("bipartite|merge|norm|sugiyama|tree", layouts)]
par(mfrow=c(3,3), mar=c(1,1,1,1))
for (layout in layouts) {
print(layout)
l <- do.call(layout, list(net))
plot(net, edge.arrow.mode=0, layout=l, main=layout) }
dev.off()
# -------~~ Highlighting aspects of the network --------
plot(net)
# Notice that our network plot is still not too helpful.
# We can identify the type and size of nodes, but cannot see
# much about the structure since the links we're examining are so dense.
# One way to approach this is to see if we can sparsify the network.
hist(links$weight)
mean(links$weight)
sd(links$weight)
# There are more sophisticated ways to extract the key edges,
# but for the purposes of this exercise we'll only keep ones
# that have weight higher than the mean for the network.
# We can delete edges using delete_edges(net, edges)
# or, by the way, add edges with add_edges(net, edges)
cut.off <- mean(links$weight)
net.sp <- delete_edges(net, E(net)[weight<cut.off])
plot(net.sp, layout=layout_with_kk)
# Another way to think about this is to plot the two tie types
# (hyperlinks and mentions) separately. We will do that in
# section 5 of this tutorial: Plotting multiplex networks.
# We can also try to make the network map more useful by
# showing the communities within it.
# Community detection (by optimizing modularity over partitions):
clp <- cluster_optimal(net)
class(clp)
clp$membership
# Community detection returns an object of class "communities"
# which igraph knows how to plot:
plot(clp, net)
# We can also plot the communities without relying on their built-in plot:
V(net)$community <- clp$membership
colrs <- adjustcolor( c("gray50", "tomato", "gold", "yellowgreen"), alpha=.6)
plot(net, vertex.color=colrs[V(net)$community])
# -------~~ Highlighting specific nodes or links --------
# Sometimes we want to focus the visualization on a particular node
# or a group of nodes. Let's represent distance from the NYT:
dist.from.NYT <- distances(net, v=V(net)[media=="NY Times"], to=V(net), weights=NA)
# Set colors to plot the distances:
oranges <- colorRampPalette(c("dark red", "gold"))
col <- oranges(max(dist.from.NYT)+1)
col <- col[dist.from.NYT+1]
plot(net, vertex.color=col, vertex.label=dist.from.NYT, edge.arrow.size=.6,
vertex.label.color="white")
# We can also highlight paths between the nodes in the network.
# Say here between MSNBC and the New York Post:
news.path <- shortest_paths(net,
from = V(net)[media=="MSNBC"],
to = V(net)[media=="New York Post"],
output = "both") # both path nodes and edges
# Generate edge color variable to plot the path:
ecol <- rep("gray80", ecount(net))
ecol[unlist(news.path$epath)] <- "orange"
# Generate edge width variable to plot the path:
ew <- rep(2, ecount(net))
ew[unlist(news.path$epath)] <- 4
# Generate node color variable to plot the path:
vcol <- rep("gray40", vcount(net))
vcol[unlist(news.path$vpath)] <- "gold"
plot(net, vertex.color=vcol, edge.color=ecol,
edge.width=ew, edge.arrow.mode=0)
# Highlight the edges going into or out of a vertex, for instance the WSJ.
# For a single node, use 'incident()', for multiple nodes use 'incident_edges()'
inc.edges <- incident(net, V(net)[media=="Wall Street Journal"], mode="all")
# Set colors to plot the selected edges.
ecol <- rep("gray80", ecount(net))
ecol[inc.edges] <- "orange"
vcol <- rep("grey40", vcount(net))
vcol[V(net)$media=="Wall Street Journal"] <- "gold"
plot(net, vertex.color=vcol, edge.color=ecol)
# Or we can highlight the immediate neighbors of a vertex, say WSJ.
# The 'neighbors' function finds all nodes one step out from the focal actor.
# To find the neighbors for multiple nodes, use 'adjacent_vertices()'.
# To find node neighborhoods going more than one step out, use function 'ego()'
# with parameter 'order' set to the number of steps out to go from the focal node(s).
neigh.nodes <- neighbors(net, V(net)[media=="Wall Street Journal"], mode="out")
# Set colors to plot the neighbors:
vcol[neigh.nodes] <- "#ff9d00"
plot(net, vertex.color=vcol)
# Another way to draw attention to a group of nodes:
plot(net, mark.groups=c(1,4,5,8), mark.col="#C5E5E7", mark.border=NA)
# Mark multiple groups:
plot(net, mark.groups=list(c(1,4,5,8), c(15:17)),
mark.col=c("#C5E5E7","#ECD89A"), mark.border=NA)
# -------~~ Interactive plotting with 'tkplot' --------
# R and igraph offer interactive plotting capabilities
# (mostly helpful for small networks)
tkid <- tkplot(net) #tkid is the id of the tkplot
l <- tkplot.getcoords(tkid) # grab the coordinates from tkplot
plot(net, layout=l)
# ================ 4. Plotting two-mode networks ================
head(nodes2)
head(links2)
net2
plot(net2)
# This time we will make nodes look different based on their type.
# Media outlets are blue squares, audience nodes are orange circles:
V(net2)$color <- c("steel blue", "orange")[V(net2)$type+1]
V(net2)$shape <- c("square", "circle")[V(net2)$type+1]
# Media outlets will have name labels, audience members will not:
V(net2)$label <- ""
V(net2)$label[V(net2)$type==F] <- nodes2$media[V(net2)$type==F]
V(net2)$label.cex=.6
V(net2)$label.font=2
plot(net2, vertex.label.color="white", vertex.size=(2-V(net2)$type)*8)
# igraph has a built-in bipartite layout, though it's not the most helpful:
plot(net2, vertex.label=NA, vertex.size=7, layout=layout_as_bipartite)
# Using text as nodes:
par(mar=c(0,0,0,0))
plot(net2, vertex.shape="none", vertex.label=nodes2$media,
vertex.label.color=V(net2)$color, vertex.label.font=2,
vertex.label.cex=.95, edge.color="gray70", edge.width=2)
dev.off()
# Using images as nodes
# You will need the 'png' package to do this:
# install.packages("png")
library("png")
# Download the images from the web:
download.file("https://kateto.net/workshops/data/images/news.png",
"news.png", mode = "wb")
download.file("https://kateto.net/workshops/data/images/user.png",
"user.png", mode = "wb")
# Read them in:
img.1 <- readPNG("news.png")
img.2 <- readPNG("user.png")
V(net2)$raster <- list(img.1, img.2)[V(net2)$type+1]
par(mar=c(3,3,3,3))
plot(net2, vertex.shape="raster", vertex.label=NA,
vertex.size=16, vertex.size2=16, edge.width=2)
# By the way, you can also add any image you want to any plot.
# For example, many network graphs could be improved by a photo
# of a tiny puppy in a teacup.
download.file("https://kateto.net/workshops/data/images/puppy.png",
"puppy.png", mode = "wb")
img.3 <- readPNG("puppy.png")
rasterImage(img.3, xleft=-1.4, xright=-0.4, ybottom=-1.4, ytop=-0.2)
# The numbers after the image are coordinates for the plot.
# The limits of your plotting area are given in par()$usr
dev.off()
detach("package:png")
# We can also generate and plot bipartite projections for the two-mode network:
# (co-memberships are easy to calculate by multiplying the network matrix by
# its transposed matrix, or using igraph's bipartite.projection function)
net2.bp <- bipartite.projection(net2)
# We can calculate the projections manually as well:
# as_incidence_matrix(net2) %*% t(as_incidence_matrix(net2))
# t(as_incidence_matrix(net2)) %*% as_incidence_matrix(net2)
par(mfrow=c(1,2))
plot(net2.bp$proj1, vertex.label.color="black", vertex.label.dist=1,
vertex.label=nodes2$media[!is.na(nodes2$media.type)])
plot(net2.bp$proj2, vertex.label.color="black", vertex.label.dist=1,
vertex.label=nodes2$media[ is.na(nodes2$media.type)])
dev.off()
# PSA: Remember to detach packages when you are done with them!
# You may run into problems if you have igraph and Statnet packages loaded together.
detach("package:igraph")
# ================ 5. Plotting multiplex networks ================
# In some cases, the networks we want to plot are multigraphs:
# they can have multiple edges connecting the same two nodes.
#
# A related concept, multiplex networks, contain multiple types of ties
# -- e.g. friendship, romantic, and work relationships between individuals.
# In our example network, we also have two tie types: hyperlinks and mentions.
# One thing we can do is plot each type of tie separately:
library("igraph")
E(net)$width <- 2
plot(net, edge.color=c("dark red", "slategrey")[(E(net)$type=="hyperlink")+1],
vertex.color="gray40", layout=layout_in_circle, edge.curved=.3)
# Another way to delete edges using the minus operator:
net.m <- net - E(net)[E(net)$type=="hyperlink"]
net.h <- net - E(net)[E(net)$type=="mention"]
# Plot the two links separately:
par(mfrow=c(1,2))
plot(net.h, vertex.color="orange", layout=layout_with_fr, main="Tie: Hyperlink")
plot(net.m, vertex.color="lightsteelblue2", layout=layout_with_fr, main="Tie: Mention")
dev.off()
# Make sure the nodes stay in the same place in both plots:
par(mfrow=c(1,2),mar=c(1,1,4,1))
l <- layout_with_fr(net)
plot(net.h, vertex.color="orange", layout=l, main="Tie: Hyperlink")
plot(net.m, vertex.color="lightsteelblue2", layout=l, main="Tie: Mention")
dev.off()
# In our example network, we don't have node dyads connected by multiple
# types of connections (we never have both a 'hyperlink' and a 'mention'
# tie between the same two news outlets) -- however that could happen.
# One challenge in visualizing multiplex networks is that multiple
# edges between the same two nodes may get plotted on top of each
# other in a way that makes them impossible to distinguish.
# For example, let us generate a simple multiplex network with
# two nodes and three ties between them:
multigtr <- graph( edges=c(1,2, 1,2, 1,2), n=2 )
l <- layout_with_kk(multigtr)
# Let's just plot the graph:
plot(multigtr, vertex.color="lightsteelblue", vertex.frame.color="white",
vertex.size=40, vertex.shape="circle", vertex.label=NA,
edge.color=c("gold", "tomato", "yellowgreen"), edge.width=10,
edge.arrow.size=5, edge.curved=0.1, layout=l)
# Because all edges in the graph have the same curvature, they are drawn
# over each other so that we only see the last one. What we can do is
# assign each edge a different curvature. One useful function in 'igraph'
# called curve_multiple() can help us here. For a graph G, curve.multiple(G)
# will generate a curvature for each edge that maximizes visibility.
plot(multigtr, vertex.color="lightsteelblue", vertex.frame.color="white",
vertex.size=40, vertex.shape="circle", vertex.label=NA,
edge.color=c("gold", "tomato", "yellowgreen"), edge.width=10,
edge.arrow.size=5, edge.curved=curve_multiple(multigtr), layout=l)
dev.off()
detach("package:igraph")
# ================ 6. Beyond igraph: Statnet, ggraph, and simple charts ================
# The 'igraph' package is only one of many available network visualization options in R.
# This section provides a few quick examples illustrating other available approaches to
# static network visualization.
# -------~~ A 'network' package example (for Statnet users) --------
# Plotting with the 'network' package is very similar to that with 'igraph' -
# although the notation is slightly different (a whole new set of parameter names!)
# Here is a quick example using the (by now very familiar) media network.
#Just in case we have forgotten this earlier:
dev.off()
detach("package:igraph")
# Load our main package:
library("network")
# Wait, what did our data look like?
head(links)
head(nodes)
# Convert the data into the network format used by the Statnet family.
# As in igraph, we can generate a 'network' object from an edgelist,
# an adjacency matrix, or an incidence matrix.
?edgeset.constructors
# Remember to set the ignore.eval to F for weighted networks.
net3 <- network(links, vertex.attr=nodes, matrix.type="edgelist",
loops=T, multiple=F, ignore.eval = F)
net3
# You can access the edges, vertices, and the network matrix using:
net3[,]
net3 %n% "net.name" <- "Media Network" # network attribute
net3 %v% "media" # Node attribute
net3 %e% "type" # Edge attribute
net3 %v% "col" <- c("gray70", "tomato", "gold")[net3 %v% "media.type"]
# plot the network:
plot(net3, vertex.cex=(net3 %v% "audience.size")/7, vertex.col="col")
# For a full list of parameters that you can use in this plot,
# check out ?plot.network.
?plot.network
# Note that - as in igraph - the plot returns the node position coordinates.
l <- plot(net3, vertex.cex=(net3 %v% "audience.size")/7, vertex.col="col")
plot(net3, vertex.cex=(net3 %v% "audience.size")/7, vertex.col="col", coord=l)
# The network package also offers the option to edit a plot interactively,
# by setting the parameter interactive=T
plot(net3, vertex.cex=(net3 %v% "audience.size")/7, vertex.col="col", interactive=T)
detach("package:network")
# -------~~ A 'ggraph' package example (for ggplot2 fans) --------
# The 'ggplot2' package and its extensions are known for offering the most
# meaningfully structured and advanced way to visualize data in R.
# In ggplot2, you can select from a variety of visual building blocks
# and add them to your graphics one by one, a layer at a time.
# The 'ggraph' package takes this principle and extends it to network data.
# Here we'll just cover the basics: for a deeper look, it would be best
# to get familiar with ggplot2 first, then learn the specifics of ggraph.
library(ggraph)
library(igraph)
# We can use our 'net' igraph object directly with the 'ggraph' package.
# The following code gets the data and adds layers for nodes and links.
ggraph(net) +
geom_edge_link() + # add edges to the plot
geom_node_point() # add nodes to the plot
# You will recognize some graph layouts familiar from igraph plotting:
# 'star', 'circle', 'grid', 'sphere', 'kk', 'fr', 'mds', 'lgl', etc.
ggraph(net, layout="lgl") +
geom_edge_link() +
ggtitle("Look ma, no nodes!") # add title to the plot
# Use geom_edge_link() for straight edges, geom_edge_arc() for curved ones, and
# geom_edge_fan() to make sure any overlapping multiplex edges will be fanned out.
# As in other packages, here we can set visual properties for the network plot by
# using various parameters, for nodes ('color', 'fill', 'shape', 'size', 'stroke')
# and edges ('color', 'width', 'linetype'). Here too 'alpha' controls transparency.
ggraph(net, layout="lgl") +
geom_edge_fan(color="gray50", width=0.8, alpha=0.5) +
geom_node_point(color=V(net)$color, size=8) +
theme_minimal()
# As in ggplot2, we can add different themes to the plot. For a cleaner look,
# you can use an empty theme with theme_minimal() and theme_void()
ggraph(net, layout = 'linear') +
geom_edge_arc(color = "orange", width=0.7) +
geom_node_point(size=5, color="gray50") +
theme_void()
# 'ggraph' also uses the 'ggplot2' way of mapping aesthetics: that is
# to say specifying which elements of the data should correspond to different
# visual properties of the graphic. This is done using the aes() function
# that matches visual parameters with attribute names from the data.
ggraph(net, layout="lgl") +
geom_edge_link(aes(color = type)) + # colors by edge type
geom_node_point(aes(size = audience.size)) + # size by audience size
theme_void()
# The edge attribute 'type' and node attribute 'audience.size' are
# taken from our data as they are included in the igraph object 'net'
# One great thing about ggplot2 and ggraph is that they automatically
# generate a legend which makes plots easier to interpret.
# We can add node labels with geom_node_text() or geom_node_label():
ggraph(net, layout = 'lgl') +
geom_edge_arc(color="gray", strength=0.3) +
geom_node_point(color="orange", aes(size = audience.size)) +
geom_node_text(aes(label = media), color="gray50", repel=T) +
theme_void()
# Note that 'ggraph' offers a number of other interesting ways to represent
# networks(e.g. dendrograms, treemaps, hive plots, circle plots)
detach("package:ggraph")
# -------~~ Other ways to represent a network --------
# This section is a reminder that there are other ways to represent a network.
# For example, we can create a heatmap of a network matrix.
# First, we'll extract a matrix from our igraph network object.
netm <- as_adjacency_matrix(net, attr="weight", sparse=F)
colnames(netm) <- V(net)$media
rownames(netm) <- V(net)$media
# Generate a color palette to use in the heatmap:
palf <- colorRampPalette(c("gold", "dark orange"))
# The Rowv & Colv parameters turn dendrograms on and off
heatmap(netm[,17:1], Rowv = NA, Colv = NA, col = palf(20),
scale="none", margins=c(10,10) )
# Degree distribution
deg.dist <- degree_distribution(net, cumulative=T, mode="all")
plot( x=0:max(degree(net)), y=1-deg.dist, pch=19, cex=1.4, col="orange",
xlab="Degree", ylab="Cumulative Frequency")
# ================ 7. Simple plot animations in R ================
# If you have already installed "ndtv", you should also have
# a package used by it called "animation".
# install.packages("animation")
library("animation")
library("igraph")
# In order for this to work, you need not only the R package, but also
# an additional software called ImageMagick from imagemagick.org
# If you don't already have it, skip this part of the tutorial for now.
ani.options("convert") # Check that the package knows where to find ImageMagick
ani.options(convert="C:/Progra~1/ImageMagick-7.0.6-Q16/convert.exe")
# You can use this technique to create various (not necessarily network-related)
# animations in R by generating multiple plots and combining them in an animated GIF.
l <- layout_with_lgl(net)
saveGIF( { col <- rep("grey40", vcount(net))
plot(net, vertex.color=col, layout=l)
step.1 <- V(net)[media=="Wall Street Journal"]
col[step.1] <- "#ff5100"
plot(net, vertex.color=col, layout=l)
step.2 <- unlist(neighborhood(net, 1, step.1, mode="out"))
col[setdiff(step.2, step.1)] <- "#ff9d00"
plot(net, vertex.color=col, layout=l)
step.3 <- unlist(neighborhood(net, 2, step.1, mode="out"))
col[setdiff(step.3, step.2)] <- "#FFDD1F"
plot(net, vertex.color=col, layout=l) },
interval = .8, movie.name="network_animation.gif" )
detach("package:igraph")
detach("package:animation")