Reputation: 684
If I have nested array like this
var ar = [[[1,0],[2,0],[3,0]], [[1,0],[2,0],[3,0]]]
I want to create two svg elements, this is easy
var svg = d3.select('div.main`)
.selectAll('svg')
.data(ar)
.enter()
.append('svg')
And now I want to bind subarrays to svg selection, something like this
var g = svg.selectAll('g')
.data(function(d,i) {return d[i];})
.enter()
.append('g')
after that the data attached to g
should be
[[1,0],[2,0],[3,0]]
I know what this line is not correct .data(function(d,i) {return d[i];})
Just do not know how to explain it different way.
Upvotes: 1
Views: 145
Reputation: 38211
If I understand the question correctly,
Your are right, the issues arise from the identified line. You don't need to return d[i]
as the data for the new selection, d
represents each individual datum associated with each svg
, d[i]
represents only a one part of each datum.
If you want each datum, in its entirety, just append a g as normal:
var g = svg.append("g");
Try console.log
on g.data()
and you will see that your data is there still as you want, it is bound to each g
.
You can then use each of these datums, bound to each g
and carried over from each svg
, as data to create new features. Passing the datum looks like: .data(function(d) { return d; })
. The snippet below should help put it all together:
var data = [[[10,10],[30,30],[50,50]], [[10,20],[80,30],[50,60]] ];
var svg = d3.select('body')
.selectAll('svg')
.data(data)
.enter()
.append('svg')
.attr("height",100)
.attr("width",200);
var g = svg.append("g");
console.log("Data Bound To First G in First SVG:")
console.log(g.data()[0]);
console.log("Data Bound To Second G in Second SVG:")
console.log(g.data()[1]);
// Data is now available to make features:
g.selectAll("circle")
.data(function(d) { return d; })
.enter()
.append("circle")
.attr("r",10)
.attr("cx",function(d) { return d[0] })
.attr("cy",function(d) { return d[1] });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>
Upvotes: 2