从图表中删除线后,我无法追加新线(d3折线图)

时间:2017-11-06 02:19:18

标签: javascript d3.js

目前,我有一张传单地图和一张D3图表,我可以选择一个点并获取折线图的相关数据。我可以在折线图中添加尽可能多的线条。要删除,我创建了一个html按钮,单击我可以删除所有路径行。我遇到的问题是,一旦点击此按钮并且线条消失,我就无法追加更多内容。有谁知道如何解决这个问题?这是代码:

<div class= "timeline">
    <svg width="100%">
        <g id="lines"></g>
        <g id= "legend"></g>
    </svg>


function setUp(){
  var div = d3.select(".timeline");
  var svg = div.select("svg") //sets size of svgContainer

  x.range([0, width]);
  y.range([height, 0]);

  svg.attr("width", timelineBounds.width)
  .attr("height", timelineBounds.height);

  svg.append("rect") //sets svg rect in container
  //.style("stroke", "black")
  .style("fill", "none")
  .attr("width", 900)
  .attr("height", 150);

 var xAxis = d3.axisBottom(x).ticks(9);
 var yAxis = d3.axisLeft(y).ticks(7);

 svg.append("g") // Add the X Axis
 .attr("class", "x axis")
 .attr("transform", "translate(" + margin.left + "," + (margin.top +   height) + ")")
 .call(xAxis);

svg.append("text")      // text label for the x axis
    .attr("transform", "translate(" + (width / 2) + " ," + (height + margin.bottom + 15) + ")")
    .style("text-anchor", "middle")
    .text("Time");

svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.call(yAxis);

svg.append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 0 - margin.left)
  .attr("x",0 - (height / 2))
  .attr("dy", "1em")
  .style("text-anchor", "middle")
  .text("PM 2.5 %");
}

这是我实际绘制线条的地方:

function drawChart (){
  var svg = d3.select("div svg"); 

 // Scale the range of the data
 var valueline = d3.line()
 .x(function (d) {
 return x(d.time);
})
.y(function (d) {
  return y(d.pm25);
})

 // adds the svg attributes to container
   let lines = svg.select('#lines').selectAll('path').data(lineArray,      function (d) {
  return d.id;
}); //any path in svg is selected then assigns the data from the array
lines.exit().remove(); //remove any paths that have been removed from   the array that no longer associated data
let linesEnter = lines.enter().append("path"); // looks at data not associated with path and then pairs it
lines = linesEnter.merge(lines); //combines new path/data pairs with previous, unremoved data

lines.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr("d", d => { return valueline(d.sensorData); })
.attr("class", "line-style")
.attr("stroke", d => lineColor(d.id));

这是单击按钮时调用的函数:

function clearData(){
  d3.selectAll("#lines").remove();
}

非常感谢!

1 个答案:

答案 0 :(得分:0)

这是我最终做的事情:

function clearData(){
  lineArray = []; 
  d3.selectAll("#lines").html('');  
}