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

戏子无情 提交于 2019-12-23 08:29:30

问题


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:

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.


回答1:


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:

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.




回答2:


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};
}


来源:https://stackoverflow.com/questions/14795996/possible-to-use-a-circle-pack-layout-in-d3-js-with-fixed-circle-sizes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!