The problem is that after you .enter()
you are returning a nested array, hence your error:
Uncaught TypeError: Object [object Array] has no method 'append'
To use .filter()
, you need to apply it after the .append()
:
var data = d3.range(10);
var svg = d3.select("body").append("svg");
var shapes = svg.selectAll(".shapes")
.data(data).enter();
shapes.append("circle")
.filter(function(d){ return d < 5; })
.attr("cx", function(d, i){ return (i+1) * 25; })
.attr("cy", 10)
.attr("r", 10);
shapes.append("rect")
.filter(function(d){ return d >= 5; })
.attr("x", function(d, i){ return (i+1) * 25; })
.attr("y", 25)
.attr("width", 10)
.attr("height", 10);
Using the code above (also in this fiddle), I get the following output:
Note that you can also achieve the same effect using Array's filter method, e.g.
var shapes = svg.selectAll(".shapes")
.data(data.filter(function(d){ return d < 5; })).enter()
.append("circle")
.attr("cx", function(d, i){ return (i+1) * 25; })
.attr("cy", 10)
.attr("r", 10);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…