admin 管理员组文章数量: 1086019
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 plex 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");
});
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 plex 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");
});
Share
Improve this question
asked Jun 4, 2017 at 13:56
user3422637user3422637
4,24917 gold badges53 silver badges76 bronze badges
2
- 3 "using Array.map() for looping through the dataset, I can achieve the same functionality with much cleaner code and fewer lines"... not even close "the same functionality". Try to update, transition or put a tooltip in those rectangles with the loop approach and you'll see. D3 means Data Driven Documents. If you don't bind any data to the DOM elements, you're missing all the nice things D3 can do. – Gerardo Furtado Commented Jun 4, 2017 at 13:58
-
3
OP if you could recreate a d3 example that utilizes enter, updates, and exits, and show us how
map
produces cleaner code and fewer lines, i 'd love to see that. – Eric Guan Commented Jun 5, 2017 at 17:09
1 Answer
Reset to default 11 +100D3 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/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/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/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 pare 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 es 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/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.
本文标签: javascriptArraymap() vs d3selectAll()dataenter()Stack Overflow
版权声明:本文标题:javascript - Array.map() vs d3.selectAll().data.enter() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744081826a2530389.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论