Possible to use a circle pack layout in d3.js with

2019-06-17 01:20发布

This circle pack layout example (http://bl.ocks.org/4063269) is perfect for a project I'm working on, however it sizes all the circles relative to one another:

enter image description here

Is there a simple way to specify fixed radii for each circle?

I've scoured the source code, examples, google, and stackoverflow and can't seem to find anything helpful.

The exact sizing of circles is important to me.

2条回答
贪生不怕死
2楼-- · 2019-06-17 01:44

It is possible, and simple thing to do. The first answer is accurate, but I believe mine is simpler, more explicit, so I am attaching it too.

Please take a look at this example: jsfiddle

When you press "Constant" button, you will see something like this:

enter image description here

The key code line is this:

    pack.value(function(d) { return 100; })

This will make circle radiuses constant regardles of data. 100 can be any constant of course. You can apply this line in circle pack initialization (most likely this will be your case), or reinitialization (like in my example).

Hope this helps.

查看更多
混吃等死
3楼-- · 2019-06-17 02:00

If you follow the code in the example you gave, the size of the <circle> elements is being decided here:

node.append("circle")
  .attr("r", function(d) { return d.r; })
// ...

To fix the size of circles to, say, 50, you can do this:

node.append("circle")
  .attr("r", function(d) { return 50; })
// ...

Update

This will, however, break the layout as pointed out in the comment. To fix that, one can provide the same value to each node:

// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: node.size});
  }

  recurse(null, root);
  return {children: classes};
}

to:

// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
  var classes = [];

  function recurse(name, node) {
    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
    else classes.push({packageName: name, className: node.name, value: 1});
  }

  recurse(null, root);
  return {children: classes};
}
查看更多
登录 后发表回答