whytheq whytheq - 3 years ago 136
Javascript Question

Grid-lines are being recreated and overlaid on each other

I'm playing with some d3 code - to create the y axis I do the following :

function renderYAxis(svg) {

var yAxis = d3.svg.axis()
.orient("left")
.scale(_y.range([quadrantHeight(), 0]))
.tickFormat(d3.format("s"));

axisData = _currentData.filter(function(row) {
if ((row['filter1'] === _filter1)) {
return true;
}
}).filter(function(row) {
if ((row['filter2'] === _filter2)) {
return true;
}
}).map(function(d) {
return {
y: +d["Y"]
};
});
var minY2 = d3.min(axisData, function(d) { return d.y });
if (minY2 > 0) {
minY2 = 0;
};
_y.domain([minY2, d3.max(axisData, function(d) { return d.y })])


if (!_axesYG) {
_axesYG = svg
.append("g")
.attr("class", "y axis");
}

_axesYG
.attr("transform", function() {
return "translate(" + xStart() + "," + yEnd() + ")";
})
.transition()
.duration(1000)
.call(yAxis);

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> maybe following needs changing somehow? >>>>>>>>>>>>>>
d3.selectAll("g.y g.tick")
.append("line")
.classed("grid-line", true)
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", quadrantWidth())
.attr("y2", 0);

}


The chart has a transition but after transitioning several times some of the grid lines are reproducing and being laid on top of each other - so producing some thicker lines. I've marked above where I think the problem may be, I'm unsure how to change this code - is there a standard approach?

A full working example of the behavior is saved here: http://plnkr.co/edit/JD52TfAddZSpNR3oaMRv?p=preview

If you hit the button several times you will see it is the common grid lines that are shared before and after the transition that are being recreated and overlaid. These two:

enter image description here

Any help much appreciated.

Answer Source

Here is a simple fix (hack), since the original code structure is hard to change to follow General Update Pattern correctly:

      // remove old ones
      d3.selectAll(".grid-line.y-axis")
         .remove();

      // draw new ones
      // add a new class y-axis to avoid deleting the x axis above
      d3.selectAll("g.y g.tick")
         .append("line")
         .classed("grid-line y-axis", true)
         .attr("x1", 0)
         .attr("y1", 0)
         .attr("x2", quadrantWidth())
         .attr("y2", 0);

http://plnkr.co/edit/wdQmllRrrILtXsarXqLY?p=preview

The more correct approach is to follow the General Update Pattern: https://bl.ocks.org/mbostock/3808234

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download