meetamit meetamit - 1 month ago 10
Javascript Question

In d3.js, skip append() for null data

I'm drawing a line graph out of little circle bullets. However, the data has holes in it, which are represented by null's in my array. Naturally, wherever there's no data, there shouldn't be circles. But d3's append() method adds them anyway. How do I avoid this?

Here's a jsFiddle mockup reproducing my problem exactly.

I'm interested in NOT having that series of circles that lie on the X axis of my graph, since those are all nulls.

Relevant code from the jsfiddle link:

svg.selectAll('circle').data(values).enter()
.append('circle')// <-- I don't want to do this for null's
.attr('fill', '#c00')
.attr('r', 3)
.attr('cx', xi)
.attr('cy', yFlipped)

Answer

One option is to represent your data differently, so that you aren't dependent on the index to compute the x-coordinate. For example, if you represented each datum as an object (e.g., {x: 0, y: 0.2840042}) then you could compute the x-coordinate as x(d.x) rather than x(i).

Another option would be to set the radius to zero when the value is null, so the circles are hidden: circle.attr("r", function(d) { return d == null ? 0 : 3; }). Or, you could hide the circles: circle.style("display", function(d) { return d == null ? "none" : null; }).

You could also remove the null elements after appending them: circle.filter(function(d) { return d == null; }).remove(). That would work for the initial creation, but I wouldn't recommend it because the index would change if you reselected the elements later.

Comments