How to update selection with new data in D3?

做~自己de王妃 提交于 2019-12-25 08:15:04

问题


I'm trying to edit the data of created circles in D3. Below my code is pasted of me creating a lot of circles based on some data from graphData.

Supposed I'd want to re-arrange my circles Y position with a new dataset, by transitioning them to their new destinations. How would perform this task? I've tried using attr.("cy", function(d){return yScale(parseFloat(d))} ) to update my Y-coordinates by adding data(graphData[i], function(d){return d;}) with my new data, but this does not work.

You can take a look at my JSFiddle: http://jsfiddle.net/RBr8h/1/

Instead of the for-loop in the following code I've created circles on 2 ticks of my X-axis. I have 3 sets of data and I've used to of them in the example in the fiddle. I'd like to able to use the 3rd dataset instead of the 2 first ones on both circles.

            var circle;
            for(var i = 0;i < graphData.length;i++){
                circle = SVGbody
                    .selectAll("circle")
                    .data(graphData[i], function(d){return d;})
                    .enter()
                        .append("circle")
                        .attr("cx",xScale(0))
                        .attr("cy", yScale(minAxisY))
                        .attr("r",4)
                        .style('opacity', 0)
                        .transition()
                        .duration(1000)
                        .attr("cx", function(d){
                            return spreadCircles(i);
                        })
                        //.attr("cy", function (d, i){ return yScale(i); })
                        .style('opacity', 1)
                        .transition()
                        .duration(1500)
                            .attr("cy", function(d){return yScale(parseFloat(d))} );

Thank you for your help in advance!


回答1:


To put some flesh on Lars comment, here is a FIDDLE leveraging the enter/update/exit pattern to help you out. I have altered and simplified your code (and data) just enough to demonstrate the principle.

function updateCircles(dataset,color) {
    var circle = SVGbody
        .selectAll("circle")
        .data(dataset, function(d) { return d; });

    circle
        .exit()
        .transition().duration(750)
        .attr("r", 0)
        .remove();

    circle
        .enter()
        .append("circle");

    circle
        .attr("cx",function(d){return xScale(100);})
        .attr("cy",function(d){return yScale(parseFloat(d))})
        .attr("r",0)
        .transition().duration(1500)
        .attr("r",5)
        .style("fill", color);
};

Update fiddle with data keyed off by index...so, circles just have their position updated.



来源:https://stackoverflow.com/questions/22913145/how-to-update-selection-with-new-data-in-d3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!