7

Example: http://mbostock.github.com/d3/ex/bubble.html

enter image description here

I'm having a hard time understanding what goes on with line 16:

.data(bubble.nodes(classes(json))

And why, or where within the classes() function, the variable classes[] gets x,y,r values defined for each of its objects. Also, bubble.nodes() doesn't appear to be an actual function?

If I add a

console.log(classes)

between lines 44 and 45 - every object inside seems to be populated with x,y,r already -- but it is not apparent why this happens.

VividD
  • 10,456
  • 6
  • 64
  • 111
kratsg
  • 600
  • 1
  • 5
  • 17
  • Did you look at the [API reference for pack.nodes](https://github.com/mbostock/d3/wiki/Pack-Layout#wiki-nodes)? – mbostock Jul 17 '12 at 23:27
  • Yes - I did. It doesn't explain why `classes` inside the function has extra properties that are assigned before being based into bubble.nodes. Documentation also doesn't explain the `r` attribute. – kratsg Jul 18 '12 at 17:21
  • The `r` property is the node radius computed by the layout. – mbostock Jul 19 '12 at 00:38
  • When - in the execution of the classes() function, are the attributes added to each of the elements in the classes[] array? – kratsg Jul 19 '12 at 22:02

2 Answers2

2

The call to bubble.nodes() boils down to a call to d3.layout.pack().nodes() since bubble=d3.layout.pack(). The trick is that pack.nodes() is hardcoded to use the value key of the input's children (in this case all the packages) to size the nodes (add r) and determine position (add x and y).

In essence,

 var root = {"children": [
              {"packageName":"cluster","className":"AgglomerativeCluster","value":3938},
              {"packageName":"cluster","className":"CommunityStructure","value":3812},
              {"packageName":"cluster","className":"HierarchicalCluster","value":6714},
              {"packageName":"cluster","className":"MergeEdge","value":743}
         ]}; // This is an excerpt of the real data.

 var bubble = d3.layout.pack(); 

 // pack.nodes() assigns each element of "children" a r, x, and y based on value
 bubble.nodes(root); 

This tripped me up at first as well, you can see that classes() doesn't add r, x, and y since classes(root) doesn't have those attributes. krasnaya's answer touched on most of this but I felt that it needed a bit more explaining (at least it did for me).

sushain97
  • 2,752
  • 1
  • 25
  • 36
1

The classes() function doesn't add the attributes.. it just flattens the tree. The attributes are added inside bubble.nodes() (which is d3.layout.pack().nodes())

JSON.stringify(classes[0])
"{"packageName":"cluster","className":"AgglomerativeCluster","value":3938}"
krasnaya
  • 2,995
  • 3
  • 21
  • 19