visNetwork Continuous Colors

visNetwork is a fantastic library used to make interactive network graphs in R. It has many features to style nodes and edges but lacks a way to fill nodes using a continuous variable. ThIs can readily be achieved by using findInterval to map a continuous variable to the closest color on a color scale. In the example below a random data set is generated with a probability between zero a one attached to each node. Color is then assigned from a palette of 101 shades of blue. The resultant graph illustrates the effect of coloring using a continuous variable - higher probabilities are darker (label = node number and probability).

 1## visNetwork continuous color
 2
 3library(visNetwork)
 4library(igraph)
 5library(dplyr)
 6library(RColorBrewer)
 7
 8## define number of nodes, edges and colors
 9
10n_nodes <- 100
11n_edges <- 200
12n_cols <- 101
13pal <- colorRampPalette(brewer.pal(9, 'Blues'))(n_cols)
14
15## create graph from random edges
16## p is a variable for color coding from 0 to 1
17
18df.nodes <- data.frame(id = seq(n_nodes), p = runif(seq(n_nodes))) %>%
19  mutate(label = sprintf('n %i (%0.2f)', id, p)) %>%
20  mutate(c_ref = findInterval(p, seq(from = 0, to = 1, length.out = n_cols))) %>%
21  mutate(color = pal[c_ref])
22  
23df.edges <- data.frame(from = sample(seq(n_nodes), n_edges, replace = TRUE), to = sample(seq(n_nodes), n_edges, replace = TRUE))
24
25visNetwork(nodes = df.nodes ,edges = df.edges) %>%
26  visIgraphLayout()