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");
});
D3 allows you to select DOM elements and manipulate them using functions provided by the library. Elements are selected with select() and selectAll() methods, which return selections. Selections have operators that allow you to modify, add, or remove elements.
D3 is data driven. The data() function is used to join the specified array of data to the selected DOM elements and return the updated selection.
D3 data selections. Data selections are the core of D3's data binding API. A data selection is created by diffing an array of data against a DOM selection. This example selects . app-user DOM elements and matches them to an array of user data.
Specifying attributes. D3 provides the ability to set attributes of a selected element using the attr() function. This function takes two parameters: Attribute Name - For example, "r" to set an SVG circle's radius.
The most powerful feature in D3, which gives the very name of the library, is its ability to bind data to DOM elements. By doing this, you can manipulate those DOM elements based on the bound data in several ways, such as (but not limited to):
And so on...
If you don't bind data to the DOM elements, for instance using the map()
approach in your question (which is the same of a forEach()
), you may save a couple of lines at the beginning, but you will end up with an awkward code to deal with later. Let's see it:
Here is a very simple code, using most of your snippet, to create a bar chart using the map()
approach:
var h = 250,
w = 500,
p = 40;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var data = [{
group: "foo",
value: 14,
name: "A"
}, {
group: "foo",
value: 35,
name: "B"
}, {
group: "foo",
value: 87,
name: "C"
}, {
group: "foo",
value: 12,
name: "D"
}, {
group: "bar",
value: 84,
name: "E"
}, {
group: "bar",
value: 65,
name: "F"
}, {
group: "bar",
value: 34,
name: "G"
}, {
group: "baz",
value: 98,
name: "H"
}, {
group: "baz",
value: 12,
name: "I"
}, {
group: "baz",
value: 43,
name: "J"
}, {
group: "baz",
value: 66,
name: "K"
}, {
group: "baz",
value: 42,
name: "L"
}];
var color = d3.scaleOrdinal(d3.schemeCategory10);
var xScale = d3.scaleLinear()
.range([0, w - p])
.domain([0, d3.max(data, function(d) {
return d.value
})]);
var yScale = d3.scaleBand()
.range([0, h])
.domain(data.map(function(d) {
return d.name
}))
.padding(0.1);
data.map(function(d, i) {
svg.append("rect")
.attr("x", p)
.attr("y", yScale(d.name))
.attr("width", xScale(d.value))
.attr("height", yScale.bandwidth())
.attr("fill", color(d.group));
});
var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
.call(axis);
<script src="https://d3js.org/d3.v4.min.js"></script>
It seems to be a nice result, the bars are all there. However, there is no data bound to those rectangles. Keep this code, we'll use it in the challenge below.
Now let's try the same code, but using the idiomatic "enter" selection:
var h = 250,
w = 500,
p = 40;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var data = [{
group: "foo",
value: 14,
name: "A"
}, {
group: "foo",
value: 35,
name: "B"
}, {
group: "foo",
value: 87,
name: "C"
}, {
group: "foo",
value: 12,
name: "D"
}, {
group: "bar",
value: 84,
name: "E"
}, {
group: "bar",
value: 65,
name: "F"
}, {
group: "bar",
value: 34,
name: "G"
}, {
group: "baz",
value: 98,
name: "H"
}, {
group: "baz",
value: 12,
name: "I"
}, {
group: "baz",
value: 43,
name: "J"
}, {
group: "baz",
value: 66,
name: "K"
}, {
group: "baz",
value: 42,
name: "L"
}];
var color = d3.scaleOrdinal(d3.schemeCategory10);
var xScale = d3.scaleLinear()
.range([0, w - p])
.domain([0, d3.max(data, function(d) {
return d.value
})]);
var yScale = d3.scaleBand()
.range([0, h])
.domain(data.map(function(d) {
return d.name
}))
.padding(0.1);
svg.selectAll(null)
.data(data, function(d) {
return d.name
})
.enter()
.append("rect")
.attr("x", p)
.attr("y", function(d) {
return yScale(d.name)
})
.attr("width", function(d) {
return xScale(d.value)
})
.attr("height", yScale.bandwidth())
.attr("fill", function(d) {
return color(d.group)
});
var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
.call(axis);
<script src="https://d3js.org/d3.v4.min.js"></script>
As you can see, it's a little longer than the previous map()
method, 2 lines longer.
However, this actually binds data to those rectangles. If you console.log a D3 selection of one of those rectangles, you'll see something like this (in Chrome):
> Selection
> _groups: Array(1)
> 0: Array(1)
> 0: rect
> __data__: Object
group: "bar"
name: "G"
value: 34
Since this code actually binds data to the DOM elements, you can manipulate them in a way that would be cumbersome (to say the least) using the map()
approach. I'll show this in the next snippet, which will be used to propose a challenge.
Since your question talks about cleaner code and fewer lines, here is a challenge for you.
I created 3 buttons, one for each group in the data
array (and a fourth one for all the groups). When you click the button, it filters the data and updates the chart accordingly:
var h = 250,
w = 500,
p = 40;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var g1 = svg.append("g")
var g2 = svg.append("g")
var data = [{
group: "foo",
value: 14,
name: "A"
}, {
group: "foo",
value: 35,
name: "B"
}, {
group: "foo",
value: 87,
name: "C"
}, {
group: "foo",
value: 12,
name: "D"
}, {
group: "bar",
value: 84,
name: "E"
}, {
group: "bar",
value: 65,
name: "F"
}, {
group: "bar",
value: 34,
name: "G"
}, {
group: "baz",
value: 98,
name: "H"
}, {
group: "baz",
value: 12,
name: "I"
}, {
group: "baz",
value: 43,
name: "J"
}, {
group: "baz",
value: 66,
name: "K"
}, {
group: "baz",
value: 42,
name: "L"
}];
var color = d3.scaleOrdinal(d3.schemeCategory10);
var xScale = d3.scaleLinear()
.range([0, w - p])
.domain([0, d3.max(data, function(d) {
return d.value
})]);
var yScale = d3.scaleBand()
.range([0, h])
.domain(data.map(function(d) {
return d.name
}))
.padding(0.1);
var axis = d3.axisLeft(yScale);
var gY = g2.append("g").attr("transform", "translate(" + p + ",0)")
.call(axis);
draw(data);
function draw(data) {
yScale.domain(data.map(function(d) {
return d.name
}))
var rects = g1.selectAll("rect")
.data(data, function(d) {
return d.name
})
rects.enter()
.append("rect")
.attr("x", p)
.attr("y", function(d) {
return yScale(d.name)
})
.attr("width", 0)
.attr("height", yScale.bandwidth())
.attr("fill", function(d) {
return color(d.group)
})
.transition()
.duration(1000)
.attr("width", function(d) {
return xScale(d.value)
});
rects.transition()
.duration(1000)
.attr("x", p)
.attr("y", function(d) {
return yScale(d.name)
})
.attr("width", function(d) {
return xScale(d.value)
})
.attr("height", yScale.bandwidth())
.attr("fill", function(d) {
return color(d.group)
});
rects.exit()
.transition()
.duration(1000)
.attr("width", 0)
.remove();
gY.transition().duration(1000).call(axis);
};
d3.selectAll("button").on("click", function() {
var thisValue = this.id;
var newData = thisValue === "all" ? data : data.filter(function(d) {
return d.group === thisValue;
});
draw(newData)
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<button id="foo">Foo</button>
<button id="bar">Bar</button>
<button id="baz">Baz</button>
<button id="all">All</button>
<br>
<br>
A cleaner code is somehow opinion-based, but we can easily measure size.
Thus, here is the challenge: try to create a code that does the same, but using the map()
approach, that is, without binding any data. Do all the transitions I'm doing here. The code you will try to recreate is all the code inside the on("click")
function.
After that, we'll compare the size of your code and the size of an idiomatic "enter", "update" and "exit" selections.
This challenge number 2 may be even more interesting to show D3 capabilities when it comes to binding data.
In this new code, I'm sorting the original data array after 1 second, and redrawing the chart. Then, clicking on the "update" button, I'm binding another data array to the bars.
The nice thing here is the key function, that associates each bar to each data point using, in this case, the name
property:
.data(data, function(d) {
return d.name
})
Here is the code, please wait 1 second before clicking "update":
var h = 250,
w = 500,
p = 40;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var data2 = [{
group: "foo",
value: 10,
name: "A"
}, {
group: "foo",
value: 20,
name: "B"
}, {
group: "foo",
value: 30,
name: "C"
}, {
group: "foo",
value: 40,
name: "D"
}, {
group: "bar",
value: 50,
name: "E"
}, {
group: "bar",
value: 60,
name: "F"
}, {
group: "bar",
value: 70,
name: "G"
}, {
group: "baz",
value: 80,
name: "H"
}, {
group: "baz",
value: 85,
name: "I"
}, {
group: "baz",
value: 90,
name: "J"
}, {
group: "baz",
value: 95,
name: "K"
}, {
group: "baz",
value: 100,
name: "L"
}];
var data = [{
group: "foo",
value: 14,
name: "A"
}, {
group: "foo",
value: 35,
name: "B"
}, {
group: "foo",
value: 87,
name: "C"
}, {
group: "foo",
value: 12,
name: "D"
}, {
group: "bar",
value: 84,
name: "E"
}, {
group: "bar",
value: 65,
name: "F"
}, {
group: "bar",
value: 34,
name: "G"
}, {
group: "baz",
value: 98,
name: "H"
}, {
group: "baz",
value: 12,
name: "I"
}, {
group: "baz",
value: 43,
name: "J"
}, {
group: "baz",
value: 66,
name: "K"
}, {
group: "baz",
value: 42,
name: "L"
}];
var color = d3.scaleOrdinal(d3.schemeCategory10);
var xScale = d3.scaleLinear()
.range([0, w - p])
.domain([0, d3.max(data, function(d) {
return d.value
})]);
var yScale = d3.scaleBand()
.range([0, h])
.domain(data.map(function(d) {
return d.name
}))
.padding(0.1);
svg.selectAll(".bars")
.data(data, function(d) {
return d.name
})
.enter()
.append("rect")
.attr("class", "bars")
.attr("x", p)
.attr("y", function(d) {
return yScale(d.name)
})
.attr("width", function(d) {
return xScale(d.value)
})
.attr("height", yScale.bandwidth())
.attr("fill", function(d) {
return color(d.group)
})
var axis = d3.axisLeft(yScale);
var gY = svg.append("g").attr("transform", "translate(" + p + ",0)")
.call(axis);
setTimeout(function() {
data.sort(function(a, b) {
return d3.ascending(a.value, b.value)
});
yScale.domain(data.map(function(d) {
return d.name
}));
svg.selectAll(".bars").data(data, function(d) {
return d.name
})
.transition()
.duration(500)
.attr("y", function(d) {
return yScale(d.name)
})
.attr("width", function(d) {
return xScale(d.value)
});
gY.transition().duration(1000).call(axis);
}, 1000)
d3.selectAll("button").on("click", function() {
svg.selectAll(".bars").data(data2, function(d) {
return d.name
})
.transition()
.duration(500)
.attr("y", function(d) {
return yScale(d.name)
})
.attr("width", function(d) {
return xScale(d.value)
});
gY.transition().duration(1000).call(axis);
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<button>Update</button>
<br>
<br>
Your challenge here is the same: change the code inside .on("click")
, which is just this...
svg.selectAll(".bars").data(data2, function(d) {
return d.name
})
.transition()
.duration(500)
.attr("y", function(d) {
return yScale(d.name)
})
.attr("width", function(d) {
return xScale(d.value)
});
gY.transition().duration(1000).call(axis);
... to a code that does the same, but for your map()
approach.
Bear in mind that, since I sorted the bars, you cannot change them by the index of your data array anymore!
The map()
approach may save you 2 lines when you first draw the elements. However, it will make things terribly cumbersome later on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With