D3在动态折线图中添加点

时间:2017-07-07 18:04:17

标签: javascript jquery d3.js

我有一个滚动的折线图,当数据进入时,它会实时更新。这是折线图的js小提琴。 https://jsfiddle.net/eLu98a6L/

我想要做的是用点图替换线,因此每个点都会创建一个点,并保持滚动功能。这是我想要创建的图表类型{{3最后我想删除下面的一行。

这是我用来尝试在图表中添加点的代码。

g.append("g")
.selectAll("dot")
.data(4)
.enter("circle")
.attr("cx", "2")
.attr("cy", "2");

到目前为止,我还没有取得任何成功。我对d3很新,所以对任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:1)

根据您的代码,可以采用以下方法:

var circleArea = g.append('g'); /* added this to hold all dots in a group */
function tick() {

  // Push a new data point onto the back.
  data.push(random());
  // Redraw the line.

  /* hide the line as you don't need it any more 
  d3.select(this)
      .attr("d", line)
      .attr("transform", null);
  */

  circleArea.selectAll('circle').remove(); // this makes sure your out of box dots will be remove.

  /* this add dots based on data */
  circleArea.selectAll('circle')
    .data(data)
    .enter()
         .append('circle')
         .attr('r',3)  // radius of dots 
         .attr('fill','black') // color of dots
         .attr('transform',function(d,i){ return 'translate('+x(i)+','+y(d)+')';}); 

  /* here we can animate dots to translate to left for 500ms */
  circleArea.selectAll('circle').transition().duration(500)
    .ease(d3.easeLinear)
    .attr('transform',function(d,i){ 
         if(x(i )<=0) {   // this makes sure dots are remove on x=0
              d3.select(this).remove();
         }
         return 'translate('+x(i-1)+','+y(d)+')';
    }); 

   /* here is rest of your code */ 
  // Slide it to the left.
  d3.active(this)
      .attr("transform", "translate(" + x(-1) + ",0)")
      .transition()
      .on("start", tick);
  // Pop the old data point off the front.
  data.shift();
}

查看实际操作:https://codepen.io/FaridNaderi/pen/weERBj

希望它有所帮助:)