1

我刚刚开始使用 d3.js(大约 1.5 周)。我想知道——大多数例子都使用一些模式,比如

mysvg.selectAll("rect").data(mydata,key).transition()...;

现在我的代码如下所示。我希望能够将时间序列绘制为特定时间之后的点和线(如果它们在特定时间之前)的矩形。我知道可以将它们作为一个系列并应用过滤器,但我想知道是否有更好的方法可以使用一个 select 语句绘制系列。

如果没有,我该如何使用过滤器来实现它?特别是,我对如何使用出口感到困惑,以便随着时间的增加,条形消失。我尝试了几种不同的方式来调用 .exit().remove(),但它似乎不起作用。

function drawChart(svgarea,mydata,key)
{   

var g = svgarea.append("svg:g");


var rects = g.selectAll("rect").data(mydata,key).enter().append("rect");
var lines = g.selectAll("line").data(mydata,key).enter().append("line");

drawAxis();

chartData = [];
chartData.redraw = function(timeIndex)
{                       
    rects.filter(function(d){
            var isAfter =  ...;
            return isAfter;})
        .transition().duration(500)
                    .attr(...,...);});  
    lines.filter(function(d){
            var isBefore =  ...;
            return isBefore;})
        .transition().duration(500)
                    .attr(...,...);});
    rects.exit().remove();  
}
chartData.redraw(0);
return chartData;
}

Note: I set it up like this because the data is non-static. The user of this little graph will call chart.redraw() after an update to the data has been made (at least that's the idea)

4

1 回答 1

1

You should split your data before you join it with your selection. Keep in mind that many of the iteration methods in d3, including filter, are based off of methods provided by the Array Object in JavaScript.

rectData = myData.filter(function(d) { /* filter conditions */ }
lineData = myData.filter(function(d) { /* filter conditions */ }

More info: array.filter(callback[, thisObject])

Then, you can just focus on update and enter() without having to filter your data every time you redraw.

于 2012-07-12T21:43:45.903 回答