I want to plot a network using the visNetwork package. I would like my nodes across all the different networks using the same colors for the same groups. So I want
- group A -> blue
- group B -> yellow
- group C -> red.
which are the first 3 default colors. Here is a first simple example:
nodes <- data.frame(id = 1:10, label = paste("Label", 1:10),
group = factor(c("A","B","C", "A","C","C","C","A","A","A"), levels=c("A","B","C")))
visnw <- visNetwork(nodes, edges) %>%
visLegend(position = "right")
visnw
But when I omit group B the color "red" disappears even when I specify that column 'group' is a factor containing 3 levels, this fact is ignored in the visualisation. Moreover, when the first element is not "A" this are shuffled even more.
nodes <- data.frame(id = 1:10, label = paste("Label", 1:10),
group = factor(c("C","A","C", "A","C","C","C","A","A","A"),c("A","B","C"))) %>%
dplyr::arrange(group) #needed to have A as first group but it doesn't seem to have an effect on the second visualisation
edges <- data.frame(from = c(2,5,10), to = c(1,2,10))
visnw <- visNetwork(nodes, edges) %>%
visLegend(position = "right")
visnw
However, the above code gives me this which is wrong because group C must have color red. Moreover the groups are switched because nodes 1,3,5,6,7 belong to group "C" and not "A". This latter problem doesn't ariwe when I omit the arrange(), but then the legend has level "C" on top and below level "A" which isn't nice.
I have tried to edit the list visnw, but this doesn't work.
I almost can achieve what I want by explicitly defining the colors I want for each group.
visnw <- visNetwork(nodes, edges) %>%
visGroups(groupname = "A", color = "lightblue") %>%
visGroups(groupname = "B", color = "yellow") %>%
visGroups(groupname = "C", color = "red") %>%
visLegend(position = "right")
visnw
This gives me this visualisation:
I prefer to use the default colors, since I like them and there is also an edge on the node in the default scheme which I should have to define manually as well. Anybody knows how to achieve this?


