I am trying to understand what's benefit of using d3.selectAll.data.enter() to loop through a dataset and plot it.
var data = [4, 8, 15, 16, 23, 42];
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);
let chartsvg = d3.select(".chart").append("svg");
chartsvg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", function(d, i) {
return 25*i;
})
.attr("width", function(d) {
return x(d);
})
.attr("height", 20)
.attr("fill", "#f3b562");
I see a lot of benefit of d3's functionalities like scale, axes, etc. But it feels like using Array.map() for looping through the dataset, I can achieve the same functionality with much cleaner code and fewer lines, especially when I am creating a much more complex visualization and not a simple barebones bar chart like this.
var data = [4, 8, 15, 16, 23, 42];
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);
let chartsvg = d3.select(".chart").append("svg");
data.map(function(d, i){
chartsvg.append("rect")
.attr("x", 0)
.attr("y", 25*i)
.attr("width", x(d))
.attr("height", 20)
.attr("fill", "#f3b562");
});
See Question&Answers more detail:os