Laci Laci - 1 month ago 8
Javascript Question

D3.js redraw chart after brushing

I am working on a D3.js chart where I would like to brush on a timeline. I stucked when I want to redraw the chart with the new data.

┬┤function brushed() {

var startDate=new Date(brush.extent()[0]);
var endDate=new Date(brush.extent()[1]);

var newDates=[];

var i=0;

while(JSONdata.measurementPoints[i].measurementDateTime<=endDate){
if(JSONdata.measurementPoints[i].measurementDateTime>=startDate){
newDates.push(JSONdata.measurementPoints[i].measurementDateTime);
}
i++;
}
if(newDates.length>0){
chart.select('path').attr('d',pathGenerator(newDates));
chart.select(".x.axis").call(xAxis);
}
}┬┤


My problem is that after I change the data on the element the whole graph disappear. I am pretty rookie in D3.js and dont really know if this is the best way to achive this functionality.

I appreciate any suggestion.

Code: http://codepen.io/laczko090/pen/ozJANP?editors=1010

Thanks in advance!

xli xli
Answer

You need to redraw the main graph line and axes in brushed.

Modified CodePen

Save a reference to the graph line's path:

var path = series.append('path')
    .attr('vector-effect', 'non-scaling-stroke')

[...]

In brushed, redraw:

path.attr('d', pathGenerator(dates));

xAxis.scale(xScale);
xAxisEl.call(xAxis);