score:11
D3 stands for Data-Driven Documents
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):
- Sort
- Filter
- Translate
- Style
- Append
- Remove
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:
The map() approach
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.
Enter selections
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.
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.
Chalenge #2
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!
Conclusion
The map()
approach may save you 2 lines when you first draw the elements. However, it will make things terribly cumbersome later on.
Source: stackoverflow.com
Related Query
- Importing JSON data to D3.js + Google Map through an internal array
- How to map json data containing an array of datas and one date?
- Map data from an array for only some keys (not filtered)
- d3.csv map data as an array
- Filtering GeoJSON data using array of values to create Leaflet map
- D3js take data from an array instead of a file
- D3.js: Get an array of the data attached to a selection?
- Using an associative array as data for D3
- D3.js - JSON data array is binding the same array element to everything
- Creating D3 map of ellipse envelope data
- D3: Grayscale image display driven by 2D array data
- How to load data from an internal JSON array rather than from an external resource / file for a collapsible tree in d3.js?
- D3 force layout: How to index data by its ID instead of its index in "nodes" array
- Displaying Data from Multidimensional Array in D3.js
- Read csv data with D3.csv, each column in separate array
- How to apply specific colors to D3.js map based on data values?
- d3.js - max and min value from json data which has array of values
- Traverse Array of objects to generate d3 Sankey Chart data
- D3 Stacked Chart with array or JSON data
- d3.json method doesn't return my data array
- D3 loop array inside data object
- Copy data from csv into array in D3
- How to map data such that I can use it to generate pie chart?
- Initiate D3.js data map with new data
- Merging arrays that hold CSV data into one object array
- D3 - Rendering Multiple Years' Worth of State Data on US Map
- how to dynamically place lat, lon data onto a topoJSON map
- Javascript manipulate data into array of object for d3 stacked chart
- d3.selectAll enter exit of nested key value pairs -- aka: how do array selections work?
- Color regions in a D3 map based on external data
More Query from same tag
- D3 updating data but not axis
- d3 append() with function argument
- Error: <circle> attribute cx: Expected length, "NaN" and Error: <circle> attribute cy: Expected length, "NaN"
- Text transformation and Datetime format issue on Linechart Zoom D3 V4
- Load multiple SVGs into javascript array without DOM append
- D3 Bar chart - Remove labels with zero value
- Line chart zoom for multiseries d3js v5 chart
- D3 TopoJSON rendering artifact
- Why is my zoom wrong in this d3 code?
- Collapsible D3 force directed graph with non-tree data
- How to Format X-axis tick values in C3.js
- Connecting border lines in D3 JS county map of US on hover
- Dynamically edit value
- Why are my D3.js circles not being created and removed as live data is generated?
- Continuously changing bundle coloring in D3 bundle layout
- How can I use crossfilter to filter graph data and visualize them on a force directed graph?
- Convert a d3 chart to load data from json inside a variable
- Javascript running intensive visualization operation without freezing the browser
- d3js / nvd3 - graph half hidden
- transition when adding new data to d3 streamgraph
- Set domain on ordinal scale from tsv data
- Using on click & selectAll to remove existing data
- How to draw an SVG Polyline in right to left direction using D3
- D3.js - links are not showing on a map (Leaflet)
- How to add vertical grid line to my d3 chart
- pandas to_json , django and d3.js for visualisation
- send query string via queue.defer
- d3.js setting x position of rect on time.scale
- D3 wordcloud add background color for each term/word
- D3 zoom translateExtent calculation when target smaller than container