[英]How to update selection with new data in D3?
I'm trying to edit the data of created circles in D3. 我正在尝试编辑D3中创建的圆的数据。 Below my code is pasted of me creating a lot of circles based on some data from
graphData
. 在我的代码下面粘贴了我根据
graphData
一些数据创建许多圆的信息。
Supposed I'd want to re-arrange my circles Y position with a new dataset, by transitioning them to their new destinations. 假设我想通过将新的数据集转移到新的目标位置来重新排列我的圆圈Y位置。 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. 我试过使用
attr
。(“ cy”, function(d){return yScale(parseFloat(d))}
)通过添加data(graphData[i], function(d){return d;}
)与我的新数据,但这不起作用。
You can take a look at my JSFiddle: http://jsfiddle.net/RBr8h/1/ 您可以看一下我的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. 我没有在以下代码中进行for循环,而是在X轴的2个刻度上创建了圆圈。 I have 3 sets of data and I've used to of them in the example in the fiddle.
我有3组数据,在小提琴中的示例中我已经习惯了。 I'd like to able to use the 3rd dataset instead of the 2 first ones on both circles.
我希望能够使用第3个数据集,而不是两个圆圈上的第2个数据集。
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! 提前谢谢你的帮助!
To put some flesh on Lars comment, here is a FIDDLE leveraging the enter/update/exit pattern to help you out. 为了对Lars的评论有所帮助,以下是利用Enter / update / exit模式帮助您的FIDDLE 。 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. 用索引标记的数据更新小提琴 ...因此,圆圈仅更新了位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.