【问题标题】:how to move circles(data points) in d3.js如何在 d3.js 中移动圆圈(数据点)
【发布时间】:2017-09-04 09:47:18
【问题描述】:

我根据随机生成的数据在x-y axis 中以 waves 的形式绘制了 2 条 线,我在波浪表示上面的data points。

基于setInterval of 200 ms,我正在更新原始数据,lines(waves) 向左移动,但问题是 只有圆圈在初始间隔正在移动,并且在第二个间隔之后,圆圈没有出现在波浪上。

查看运行代码的 jsfiddle:https://jsfiddle.net/rajatmehta/tm5166e1/10/

这里是代码:

   chartBody.append("path") // Add the valueline path
  .datum(globalData)
  .attr("id", "path1")
  .attr("class", "line")
  .attr("d", valueline);

chartBody.selectAll(null)
  .data(globalData)
  .enter()
  .append("circle")
  .attr("class", "dot1")
  .attr("r", 3)
  .attr("cx", function(d) {
  console.log(d);
    return x(d.timestamp);
  })
  .attr("cy", function(d) {
    return y(d.value);
  });

chartBody.selectAll(null)
  .data(globalDataNew)
  .enter()
  .append("circle")
  .attr("class", "dot2")
  .attr("r", 3)
  .attr("cx", function(d) {
    return x(d.timestamp);
  })
  .attr("cy", function(d) {
    return y(d.value);
  });





chartBody.append("path") // Add the valueline path
  .datum(globalDataNew)
  .attr("id", "path2")
  .attr("class", "line")
  .attr("d", valueline2);

知道怎么做吗?

【问题讨论】:

    标签: javascript d3.js data-visualization


    【解决方案1】:

    您需要根据更新的数据创建新圈子。目前,您只是将数据更新为选择,而不是附加圆圈,然后将现有圆圈移动到左侧。

    例如,您可以这样做:

    chartBody.selectAll(".dot1")
      .data(globalData, function(d){ return d.timestamp; })
      .enter()
      .append("circle")
      .attr("class", "dot1")
      .attr("r", 3)
      .attr("cx", function(d) {
        return x(d.timestamp);
      })
      .attr("cy", function(d) {
        return y(d.value);
      });
    
        chartBody.selectAll(".dot2")
      .data(globalDataNew, function(d){ return d.timestamp; })
      .enter()
      .append("circle")
      .attr("class", "dot2")
      .attr("r", 3)
      .attr("cx", function(d) {
        return x(d.timestamp);
      })
      .attr("cy", function(d) {
        return y(d.value);
      });
    
      d3.selectAll(".dot1")
        //.data(globalData)
        .transition()
        .duration(duration)
        .ease("linear")
        .attr("transform", "translate(" + String(dx) + ")");
    
    
      d3.selectAll(".dot2")
        //.data(globalDataNew)
        .transition()
        .ease("linear")
        .duration(duration)
        .attr("transform", "translate(" + String(dx) + ")");
    

    请看这里:https://jsfiddle.net/tm5166e1/11/

    这会附加数据,使用时间戳作为键,因此您只需为新添加的数据创建新圆圈。

    (首次添加它们时存在一个问题,超出了本问题的范围,但值得查看以下示例:https://bl.ocks.org/tomshanley/15a2b09a95ccaf338650e50fd207fcbf 和 https://bl.ocks.org/mbostock/1642874)

    【讨论】:

    • 它可以工作,但是当线条向左移动时添加圆圈会有一些延迟。我不想这样,有什么办法可以防止吗?
    • 可能尝试使用 Mike Bosticks 示例中的剪辑路径技术,添加圆圈,并将线向右延伸,以便它们在可见时保持同步。
    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多