//add circles with price data
svgContainer.selectAll("circle")
.data(priceData)
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y1(d); })
//add circles with difficulty data
svgContainer.selectAll("circle")
.data(difficultyData)
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y2(d); })
在上半部分,沿着图表中的相关线添加带有价格数据的圆圈。现在我想对后半部分执行相同的操作,将具有不同数据的圆圈添加到不同的行。但是,第一个圆圈的数据会被第二个圆圈的数据覆盖,并且第二个圆圈永远不会被绘制。
我想我对这里发生的事情有一种直觉,但是有人可以解释一下到底做了什么以及如何解决问题吗?
可能的引用:
"The key function also determines the enter and exit selections: the new data for which there is no corresponding key in the old data become the enter selection, and the old data for which there is no corresponding key in the new data become the exit selection. The remaining data become the default update selection."
最佳答案
首先,了解 selectAll()
、data()
、enter()
从这个伟大的 post 中做什么.
问题是,由于当我们到达后半部分时,circle
元素已经存在,因此新提供的数据只是覆盖了圆圈,而不是创建新的圆圈。为了防止这种情况发生,需要在后半部分的data()
函数中指定一个key function
。然后,第一批圆圈不会被覆盖。
//add circles with price data
svgContainer.selectAll("circle")
.data(priceData)
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y1(d); })
//add circles with difficulty data
svgContainer.selectAll("circle")
.data(difficultyData, function(d) { return d; }) // SPECIFY KEY FUNCTION
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y2(d); })
关于javascript - d3js : adding same type of elements with different data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364023/