Reputation: 6185
I anm new to d3 and I would like to create a 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.
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.
Here is my try (inspired by 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; })
Upvotes: 0
Views: 176
Reputation: 108537
You almost had it. Your extra properties are in d.data
though:
<!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 d.x; })
.attr('cy', function(d) { return d.y; })
.attr('r', function(d) { return d.r; })
.attr('fill', function(d) { return d.data.fill; })
.attr('fill-opacity', function(d) {
return d.data.fillopacity;
})
</script>
</body>
</html>
Upvotes: 1