我正在尝试为一些与学生相关的数据(下面的示例记录)创建数据可视化,但是当d3渲染该数据时,它将两次遍历该数据并将其覆盖,仅第二次仅将结果保留在屏幕上。我在这里使用行计数器,因此我有一种方法可以根据有多少个矩形来设置每个矩形的y坐标。我认为这使事情有些混乱。我们将非常感谢您提供任何帮助,以确保数据不会两次迭代。
同样,以防万一,这个代码也存在于angular.js指令中。
抱歉,如果我只是在这里做一些愚蠢的事情
// student records sample...
var studentData = [
{
"studentID" : 1001,
"firstName" : "jill",
"lastName" : "smith",
"workLoadDifficulty" : 16,
"smileStartAngle" : -90,
"smileEndAngle" : 90,
},
{
"studentID" : 1008,
"firstName" : "bob",
"lastName" : "smith",
"workLoadDifficulty" : 99,
"smileStartAngle" : 90,
"smileEndAngle" : -90,
}
];
(function () {
'use strict';
angular.module('learnerApp.directives')
.directive('d3Bars', ['d3', function(d3) {
return {
restrict: 'EA',
scope: {
data: "=",
label: "@",
onClick: "&"
},
link: function(scope, iElement, iAttrs) {
var paddingForShape = 10;
var rowCounter = -1;
var height = 400;
var width = 300;
var svgContainer = d3.select(iElement[0])
.append("svg")
.attr("width", width)
.attr('height', height);
// on window resize, re-render d3 canvas
window.onresize = function() {
return scope.$apply();
};
scope.$watch(function(){
return angular.element(window)[0].innerWidth;
}, function(){
return scope.render(scope.data);
}
);
// watch for data changes and re-render
scope.$watch('studentData', function(newVals, oldVals) {
return scope.render(newVals);
}, true);
// define render function
scope.render = function(data){
// remove all previous items before render
svgContainer.selectAll("*").remove();
var workLoadColor = d3.scale.category10()
.domain([0,100])
.range(['#02FA28', '#73FA87', '#C0FAC9','#FAE4C0', '#FAC775', '#FAA823','#FA9A00','#FA8288', '#FC4750', '#FA0511' ])
var studentRects = svgContainer.selectAll('rect')
.data(studentData, function(d) {
console.log(d.studentID);
console.log('hello');
return "keyVal" + d.studentID;
})
.enter()
.append("rect");
var studentRectAttributes = studentRects
.attr("x", function(d,i) {
return ((i * 50) % width) + paddingForShape;
})
.attr("y", function(d,i) {
var value = ((i * 50) % width)
if (value === 0) {
rowCounter = rowCounter + 1;
}
var value = (rowCounter * 50);
console.log('Y Val: ', i);
console.log(value);
return value;
})
.attr("height", 30)
.attr("width", 40)
.style("fill", function(d) {
return workLoadColor(d.workLoadDifficulty)
});
};
}
};
}]);
}());
最佳答案
如果要执行两次数据联接,则需要指定key
,以免覆盖当前选择中的元素。您可能需要将studentRects
定义更改为:
var studentRects = svgContainer.selectAll('rect')
.data(studentData, function(d) { return d.firstName + ' ' + d.lastName; });
studentRects.enter().append("rect");
见
selection.data([values[, key]])
如果未指定键功能,则将指定数组中的第一个数据分配给当前选择中的第一个元素,将第二个数据分配给第二个所选元素,依此类推。