简体   繁体   中英

D3 js update plot just adds new points on top

I have a graph that has data updating every second. The limits do not change and all I want to do is clear the graph and put the new points onto it. But currently this just adds all of the points on top of the last ones.

 main.append('g')
  .attr('transform', 'translate(0,0)')
  .attr('class', 'main axis date')
  .call(yAxis); 

  g = main.append("svg:g");

function update(data){
  g.selectAll("scatter-dots")
    .data(data)  
    .enter().append("svg:circle")  // create a new circle for each value
        .attr("cy", function (d) { return y(d); } ) // translate y value to a pixel
        .attr("cx", function (d,i) { return x(xdata[i]); } ) // translate x value
        .attr("r", 4); // radius of circle
}

You should just need to add an exit() call to tell d3 to remove any points from the graph that are no longer in the dataset. Generally you will also want to use an enter (for new elements), update (for existing elements), and exit (for removed elements) strategy when working with d3 . The pattern usually looks like this:

function update(data){
  var points = g.selectAll("scatter-dots").data(data);

  points.enter().append("svg:circle");  // create a new circle for each value

  points  
    .attr("cy", function (d) { return y(d); } ) // translate y value to a pixel
    .attr("cx", function (d,i) { return x(xdata[i]); } ) // translate x value
    .attr("r", 4); // radius of circle

  points.exit().remove();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM