Reputation: 3207
I've just started using d3.js (about 1.5 weeks in). I was wondering -- most of the examples use some pattern like
mysvg.selectAll("rect").data(mydata,key).transition()...;
Right now my code looks like the following. I want to be able to draw a time series as rectangles for the points that are after a certain time and lines if they are before a certain time. I know it's possible to just have them as one series and apply filters, but I was wondering if there is a better way in which I can just draw the series using one select statement.
If not, how can I implement it using filters? Particularly, I'm confused as to how to use the exit so that the bars disappear as I increase time. I've tried several different ways of alling .exit().remove(), but it doesn't seem to work.
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)
Upvotes: 1
Views: 574
Reputation: 15695
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.
Upvotes: 1