Home > Net >  Select Specific Node NetworkD3
Select Specific Node NetworkD3

Time:06-15

Is there a way to select an specific node using NetworkD3 in order to change its color?

Here is my code. I would like to use the customJS to achieve that!

p <- forceNetwork(Links = links, 
                  Nodes = nodes, 
                  Source = 'source', 
                  Target = 'target', 
                  NodeID = 'name',
                  Group = 'group', 
                  Value = "value",
                  Nodesize = 'size',
                  radiusCalculation = JS("d.nodesize/2"),
                  zoom = TRUE, 
                  arrows = FALSE,
                  linkWidth = JS("function(d){return d.value;}"),
                  linkDistance = JS("function(d){return d.value*100}"),
                  charge = gravity,
                  opacity = 0.95,
                  fontSize = 24,
                  bounded = FALSE,
                  linkColour = "#424242"
)

customJS <- 
  "function() { 
    d3.selectAll('.node text').style('fill', 'white').attr('stroke-width', '.1px').attr('stroke', '#3f3f3f');
    d3.select('body').style('background-color', '#15171A');
    simulation = this;
    simulation.stop();
    for (var i = 0; i < 300;   i) simulation.tick();
    simulation.restart();
  }"

g <- htmlwidgets::onRender(p, customJS)

CodePudding user response:

The canonical way of controlling the color of nodes is to use the Group argument to specify a column in your nodes data.frame that specifies a group for each node. You can have a single node in a unique group and/or you can have multiple nodes in a group, and you can have as many groups as you want (at least hypothetically, but obviously limited by your machine's resources and the number of colors/groups that can effectively be seen on your screen).

By default, the color for each group is chosen automatically from the default D3 color palette. If you want to specify a different palette, or if you want to specify specific colors for specific groups, you can modify the default value for the colourScale argument.

library(networkD3)

data(MisLinks)
data(MisNodes)


MisNodes$group <- ifelse(as.character(MisNodes$name) > "M", "group_1", "group_2")

colourScale <- 'd3.scaleOrdinal().domain(["group_1", "group_2"]).range(["#FF0000", "#0000FF"]);'

forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 1, colourScale = colourScale)

enter image description here

  • Related