具有重复"值"的复杂数据对象=缺少图表栏

Jak*_*son 3 d3.js

我不确定这是不是d3错误,或者我做错了什么.看看以下内容:

http://jsfiddle.net/Jakobud/SfWjB/6/

var data = [
        { value: 20, color: 'red' },
        { value: 30, color: 'blue' },
        { value: 30, color: 'purple' }  // Same value as 2nd object
    ];

var w = 140,
    h = d3.max(data, function(d){ return d.value; }) + 30,
    barPadding = 4,
    topPadding = 1,
    bottomPadding = 20;

var svg = d3.select('#chart')
    .append('svg:svg')
    .attr('width', w)
    .attr('height', h);

var rects = svg.selectAll('rect')
    .data(data, function(d){ console.log(d); return d.value; })  // All 3 objects found here
    .enter()
    .append('rect')
    .attr('x', function(d,i){ console.log(i); return i * w / data.length + 1; })  // Last data object ignored, not placed at all
    .attr('y', function(d){ return h - d.value - topPadding - bottomPadding })
    .attr('width', w / data.length - barPadding - 3 )
    .attr('height', function(d) { return d.value })
    .attr('fill', function(d) { return d.color })
    .attr('stroke', '#333')
    .attr('stroke-width', 2);

text = svg.selectAll('text')
    .data(data, function(d){ return d.value; })
    .enter()
    .append('text')
    .text(function(d){ return d.value; })
    .attr('x', function(d,i){ return i * w / data.length + 20; })
    .attr('y', function(d,i){ return h - 0; })
    .attr("text-anchor", "middle")
    .attr("font-size", "20px")
    .attr("fill", "#333");
Run Code Online (Sandbox Code Playgroud)

您可以在我的数据对象中看到,第二个和第三个对象具有相同的"值".

在创建svg rects时,将忽略第3个数据对象,因此不会将其放置在图表中.如果将第3个对象的值从30更改为31或其他,则可以看到该栏确实显示.但由于它与第二个对象的值相同,因此它不会显示出来.

为什么是这样?你怎么防止这种情况?这里的代码是什么导致这个?该rects.data()功能看到的所有三个对象,你可以看到与console.log()我加入的功能.

Lar*_*off 5

将数据与现有数据匹配的方式导致问题,特别是线路问题

.data(data, function(d){ return d.value; })
Run Code Online (Sandbox Code Playgroud)

这告诉d3如果两个数据对象的value属性相同,则认为它们是相同的.这是第二个和第三个对象的情况,因此只添加第一个对象.如果你想要两者,你可以省略告诉d3如何比较数据对象的函数(因此依赖于数组索引匹配的默认行为),或者更改那个函数也要考虑color到.

总而言之,您所看到的不是错误,而是一个功能:)这种行为完全是预期和需要的.