D3:如何在数据绑定期间验证数据

D3: How to validate data during data binding?

本文关键字:验证 数据 数据绑定 D3      更新时间:2023-09-26

我正在尝试渲染甘特图,其中我将数据绑定在 d3 中并在两端渲染圆圈。我的数据与此结构有些相似:

function Event(start, end) {
    this.startTime = start;
    this.endTime = end;
}

我像往常一样绑定我的数据:

myplot.selectAll(".EventStart")
       .data(EventList).enter()
       .append("circle")
       .attr("class", "EventStart")
       .attr("cx", function (d) { return scaleX(d.startTime)})
       .attr("cy", function (d) { return eventRenderingHeight })
       .attr("r", 5)
       .style("fill", "white");
myplot.selectAll(".EventEnd")
       .data(EventList).enter()
       .append("circle")
       .attr("class", "EventEnd")
       .attr("cx", function (d) { return scaleX(d.endTime)})
       .attr("cy", function (d) { return eventRenderingHeight })
       .attr("r", 5)
       .style("fill", "white");

现在,这将在我的事件的开始和结束时呈现两个白色圆圈。但是如果开始时间和结束时间相同,我想省略渲染第二个圆圈。我该怎么做?

谢谢。

您可以在绑定之前过滤dataList

myplot.selectAll(".EventEnd")
           .data(EventList.filter(function(d){ return d.startTime!=d.endTime }))
           .enter()
           .append("circle")           
           .attr("class", "EventEnd")
           .attr("cx", function (d) { return scaleX(d.endTime)})
           .attr("cy", function (d) { return eventRenderingHeight })
           .attr("r", 5)
           .style("fill", "white");

过滤器如下所示。

myplot.selectAll(".EventEnd")
       .data(EventList)
       .enter()
       .append("circle")
       .filter(function(d) { return d.startTime!=d.endTime })
       .attr("class", "EventEnd")
       .attr("cx", function (d) { return scaleX(d.endTime)})
       .attr("cy", function (d) { return eventRenderingHeight })
       .attr("r", 5)
       .style("fill", "white");