Let’s reload the Game of Thrones network.
library(igraph); library(tidyverse)
edges <- read_csv("../data/GOT-edges.csv")
g <- graph_from_data_frame(d=edges, directed=FALSE)
Next, let’s load in the visNetwork
package. Make sure to install if you don’t have it.
Although not required, it’s easiest to create the network using the igraph object (g).
library(visNetwork)
visIgraph(g) %>%
visNodes(label = V(g)$name) %>% # adds labels of names
visInteraction(navigationButtons = TRUE) # adds the zoom in and out
Alternatively, we can create the edges into a visNetwork objects: edges and nodes.
One way is to use the as_data_frame() function to pull out each element into its respective object.
# create the links and nodes
edges <- igraph::as_data_frame(g, what="edges")
nodes <- igraph::as_data_frame(g, what="vertices")
# node id must be name as from/to edges
nodes$id <- nodes$name
Unlike the igraph, when using nodes/edges you can add columns to indicate properties about the nodes or edges.
For example, if you want the labels of the nodes, you can create a new column named label
.
nodes$label <- nodes$name
visNetwork(nodes, edges) %>%
visIgraphLayout() %>% # this forces a visIgraph Layout
visInteraction(navigationButtons = TRUE)
Let’s instead make the node size relative to betweenness.
First, we need to get betweenness.
b <- betweenness(g) %>%
sort(decreasing=TRUE)
head(b)
## Jon Robert Tyrion Daenerys Robb Sansa
## 1279.7534 1165.6025 1101.3850 874.8372 706.5573 705.1986
So Jon, Robert, Tyrion and Daenerys are the “gate-keepers” (highest betweenness).
nodes$size <- ((betweenness(g) / max(betweenness(g)))+.2)*40
visNetwork(nodes, edges) %>%
visIgraphLayout() %>% # this forces a visIgraph Layout
visInteraction(navigationButtons = TRUE)
Let’s run community detection using a built-in algorithm in igraph.
clp <- cluster_label_prop(g)
library(RColorBrewer) #install if you don't have it
nodes$color.background <- brewer.pal(12, "Set3")[as.factor(clp$membership)]
nodes$color.border <- "black"
edges$color <- "black"
visNetwork(nodes, edges) %>%
visIgraphLayout() %>% # this forces a visIgraph Layout
visInteraction(navigationButtons = TRUE)
Alternatively, we can change the node shape to a circle which will put the labels inside of each node. While this is more aesthetically pleasing, this removes size as proportional to Betweenness.
nodes$shape <- "circle"
visNetwork(nodes, edges) %>%
visIgraphLayout() %>% # this forces a visIgraph Layout
visInteraction(navigationButtons = TRUE)
There are a TON of different customizations with visNetwork and igraph.
Also, there are other network packages in R like ggraph
, networkD3
and edgebundleR
. Explore!
For example…
library(edgebundleR) #install if you don't have it
edgebundle(g, fontsize = 6)