[英]d3.pack(): multiple parent circles each with a unique color
I anm new to d3 and I would like to create a d3.pack. 我是d3的新手,我想创建一个d3.pack。 I am looking for tutorial and example of codes, but all the ones I find have a single parent circle whereas, I would like several of them like on this image (except the "continent" circles would each have a different color).
我正在寻找教程和代码示例,但是我发现的所有代码都有一个父圆,而我希望其中的几个像在此图像上一样 (除了“大陆”圆每个都有不同的颜色)。
I wonder how it can be done. 我不知道该怎么做。 I am new to .js and D3 so I tried to add another first level item in the JS object, but apparently it doesn't work that way.
我是.js和D3的新手,所以我尝试在JS对象中添加另一个第一级项目,但是显然,这种方式行不通。
SO now I am trying with a single first parent, but with a "fillopacity":"0.0",
so that it will be transparent, but again I couldn't make it works. 所以现在我正在尝试使用一个单亲父母,但是使用
"fillopacity":"0.0",
这样它将是透明的,但是我仍然无法使其正常工作。
Here is my try (inspired by http://d3indepth.com ) 这是我的尝试 (灵感来自http://d3indepth.com )
Some bits of the code: 代码的一些位:
var data = {
"name": "A1",
"fill": "red",
"fillopacity":"0.0",
"children": [
{
"name": "B1",
"fill": "blue",
"children": [... code cut ...]
},
{
"name": "B2",
"value": 200,
"fill": "yellow"
},
{
"name": "B3",
"value": 200,
"fill": "green"
}
]
};
d3.select('svg g')
.selectAll('circle')
.data(rootNode.descendants())
.enter()
.append('circle')
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', function(d) { return d.r; })
.attr('fill', function(d) { return d.fill; })
.attr('fill-opacity', function(d) { return d.fillopacity; })
You almost had it. 你差点就吃了。 Your extra properties are in
d.data
though: 不过,您的额外属性在
d.data
:
<!DOCTYPE html> <meta charset="utf-8"> <head> <title>Pack layout</title> </head> <body> <svg width="320" height="320"> <g></g> </svg> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> <script> var data = { "name": "A1", "fill": "red", "fillopacity":"0.0", "children": [ { "name": "B1", "fill": "blue", "children": [ { "name": "C1", "value": 100, "fill": "red" }, { "name": "C2", "value": 300, "fill": "red" }, { "name": "C3", "value": 200, "fill": "red" } ] }, { "name": "B2", "value": 200, "fill": "yellow" }, { "name": "B3", "value": 200, "fill": "green" } ] }; var packLayout = d3.pack() .size([300, 300]); var rootNode = d3.hierarchy(data) rootNode.sum(function(d) { return d.value; }); packLayout(rootNode); d3.select('svg g') .selectAll('circle') .data(rootNode.descendants()) .enter() .append('circle') .attr('cx', function(d) { return dx; }) .attr('cy', function(d) { return dy; }) .attr('r', function(d) { return dr; }) .attr('fill', function(d) { return d.data.fill; }) .attr('fill-opacity', function(d) { return d.data.fillopacity; }) </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.