Search code examples
d3.jstooltipgeometry

Transition circles and tooltip on update


I have this code to attach circles to points on a line graph.

svg.selectAll("dot")
    .data(newdata)
   .enter()
    .append("circle")
    .attr("class", "dot")
    .attr("r", 4)
    .attr("cx", function(d) { return x(newdate(d.key)); })
    .attr("cy", function(d) { return y(d.values.mean); })
    .attr("fill", "#8cc13f")
    .on("mouseover", function(d) {
        div.transition()
            .duration(200)
            .style("opacity", .9);    
        div.html("Date taken:" + "  " + newdate(d.key) + "<br/>" + "<br/>" +
                 "Average Reading:" + "  " + d.values.mean + "<br/>" + "<br/>" +
                 "Parameter:" +  "  " + selectedParameter)
           .style("left", (d3.event.pageX) + "px")
           .style("top", (d3.event.pageY - 28) + "px");
    })
    .on("mouseout", function(d) {
        div.transition()
            .duration(500)
            .style("opacity", 0);
    });

..and attempting to transition these circles when I update the graph using the following:

var circle = svg.selectAll("dot")
    .data(newdata);

circle
    .enter()
    .append("circle")
    .data(newdata)
    .transition()
    .duration(750)
    .attr("cx", function(d) { return x(newdate(d.key)); })
    .attr("cy", function(d) { return y(d.values.mean); })
    .attr("r", 4)
    .attr("fill", "#8cc13f");

circle
    .exit()
    .transition()
    .duration(750)
    .attr('opacity',0)
    .remove();

The join is working as the new circles are being added - but for some reason the old ones aren't being removed? Can anyone help?


Solution

  • The problem here is that D3 does not know how to match the data from your first data bind to your second (by default it just uses the data array's index) Adding a key function to your data binding should solve this, it defines how D3 will match up the data. See Mike Bostock's excellent Object Constancy tutorial for more information on data keys.