EnigmaRM
EnigmaRM

Reputation: 7632

d3.js animate/transition circles on update

I have a simple line graph that checks every 5 seconds for updates & redraws the line/scale if needed. This all works well EXCEPT: the data-point dots.

What am I missing in the redraw to move the dots? The dots are there when the graph is first rendered. But on update, they don't move when the line gets redrawn. So I selected a new data source on update, and the old data-points remained fixed.

Redraw on update

var svgAnimate = d3.select("#animateLine").transition();

        svgAnimate.select(".line") // change the line
            .duration(750)
            .attr("d", valueline(data));
        svgAnimate.selectAll(".circle") // change the circle
            .duration(750)
            .attr("d", valueline(data));
        svgAnimate.select(".x.axis") // change the  x axis
            .duration(750)
            .call(xAxis);
        svgAnimate.select(".y.axis") // change the y axis
            .duration(750)
            .call(yAxis);

Initial drawing:

svgAnimate.selectAll("dot")
        .data(data)
    .enter().append("circle")
        .attr("class", "circle")
        .attr("r", 5)
        .style("fill", function(d) { 
            if (d.close <= 400) {return "red"} 
            else { return "black" }
        ;})
        .attr("cx", function(d) { return x(d.date); })
        .attr("cy", function(d) { return y(d.close); })

This is what I don't want. enter image description here

Upvotes: 2

Views: 4242

Answers (2)

sanyooh
sanyooh

Reputation: 1631

I had some issues with updating circles in charts too. Here is a working fiddle and might some people for future searches if they have the same problem: http://jsfiddle.net/noo8k17n/

The problem is this line:

var svgAnimate = d3.select("#animateLine").transition();

It needs to be removed and then in the update method you can add and remove circles.

Upvotes: 0

Christopher Chiche
Christopher Chiche

Reputation: 15325

Your problem is that the function valueLine is the function you use to draw the line. Thus, when calling it again with a new data you redraw the line.

For the circles the attribute d has no sense. However, if we consider that the y axis does not change, then you can do something like:

svgAnimate.selectAll(".circle") // change the circle
    .data(newData)
    .duration(750)
    .attr("cx", function(d){return x(d.date)};

If you need to change the y coordinates, then you have to modify the cy attribute of the circle.

My code might not be as rigorous as necessary, please post a jsFiddle if you still have problems.

Upvotes: 3

Related Questions