javascript - d3js : adding same type of elements with different data

标签 javascript jquery d3.js

//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/

相关文章:

javascript - 如何在 PhoneGap 中显示长数据列表

javascript - angularjs运行命名函数

文档之间的 Javascript 和 jQuery 不起作用

jquery - 如何清除 select2 下拉列表?

jquery - 5 秒后或用户单击关闭链接时隐藏 DIV

javascript - d3 节点内的 Angular 指令

javascript - 如何在使用 window.open 时停留在当前页面

javascript - jQuery 图像悬停时闪烁

javascript - 构建 d3-tip 时的 Webpack 警告

javascript - 如何对 d3 中的形状选择进行排序