Eric Koslow
Eric Koslow

Reputation: 2064

Labeling animated line graphs using D3

I'm new to D3, and I've come across an issue I can't seem to solve.

I've built an animated line graph using this tutorial, and I'm now trying to add to it. What I thought would be a cool idea, would be to label each line in the line graph, but label it at the end of the line.

Here's what I've come up with so far:

enter image description here

As you can see its sub optimal at best. I'm positioning the text incorrectly, but whats not obvious, is how to position it the right way. Here's the code in question.

name.transition()
    .duration(duration)
    .ease("linear")
    .attr("transform", function(d) { 
      return "translate(" + (width - margin.left - margin.right) +", " + y(d[n-2]) + ")";
    });

It seems the "linear" easing is off, and it also seems to be using a different scale at times.

Is there a D3 expert (or novice) out there willing to teach me the correct way of doing this?

Upvotes: 1

Views: 578

Answers (1)

nrabinowitz
nrabinowitz

Reputation: 55678

There seem to be two issues here:

  1. .interpolate("basis") - you're using a linear interpolation for the title, but a B-spline interpolation for the path. Commenting out this line keeps the title pretty tight with your data line (though it de-smooths the line as well - probably a good thing for most data graphs).

  2. "Jumps" when the axis scale changes. This is because the title is transitioning to the new position on the new scale, but its starting position is still set relative to the old scale, so it may start above or below the line it's tracking. I think you can fix this by adding a direct .attr setting before you start the transition, to fix the initial position of the title:

    name
        .attr("transform", function(d) {
           return "translate(" +
               (width - margin.left - margin.right) +", " + y(d[n-2]) + ")"
        })
        .transition()
        // etc
    

See http://jsbin.com/uvayof/2

Upvotes: 1

Related Questions