score:3

Accepted answer

You have an array of connections links. Afterwards you extract the distinct nodes from this array by these lines:

  links.forEach(function(link) {
    link.source = nodes[link.source] || (nodes[link.source] = {name: link.source} );
    link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
  });

At this point you should insert the type for each node. So, e.g. we could use the class of the link, for this node (in that case, however, only one of all the links for a node determines its class). That would lead to the following code:

 links.forEach(function(link) {
    link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type: link.type} );
    link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type: link.type});
  });

No all nodes have a type attribute and not just a name.

When creating the circles later on here

  var circle = svg.append("svg:g").selectAll("circle")
      .data( force.nodes() )
    .enter().append("svg:circle")
      .attr("r", 6)
      .call(force.drag);

we can use that type attribute together with a function that determines each circles class like this:

  var circle = svg.append("svg:g").selectAll("circle")
      .data( force.nodes() )
    .enter().append("svg:circle")
      .attr("r", 6)
      .attr( 'class', function( d ) { console.log( d ); return d.type; } )
      .call(force.drag);

And now all circles with have the respective class.

Note that you probably want to determine the type for each node somehow different, then in this example. So change the above declaration in links.forEach( ... ); accordingly.


Related Query