使用新数据更新d3图表

时间:2018-02-23 13:48:48

标签: javascript d3.js charts mapping gis

当我在地图上点击县时,我正在尝试更新d3图表。每次都会创建一个新图表,而不是更新现有图表。有任何想法如何纠正这个?代码在这里:https://github.com/careyshan/d3-graphUpgade 感谢

这是我遇到困难的代码的一部分:

on("click", function(d,i){

              if(document.getElementById('linechart').childNodes===null){
                console.log("Working")
                dataNew = data.filter(function( obj ) {
                  return obj.County == d.properties.NAME_TAG;
                    console.log(data);
                });

                dataNew.sort(function(a,b){
                // Turn your strings into dates, and then subtract them
                // to get a value that is either negative, positive, or zero.
                return b.date - a.date;
                });
                for (var i=1; i<dataNew.length;i++){
                dataSel.push(dataNew[i]);
                }
          }else if(document.getElementById('linechart').childNodes!=null){
                //console.log("check")
                dataNew = data.filter(function( obj ) {
                  return obj.County == d.properties.NAME_TAG;
                });

                dataNew.sort(function(a,b){
                // Turn your strings into dates, and then subtract them
                // to get a value that is either negative, positive, or zero.
                return b.date - a.date;
                });
                for (var i=1; i<dataNew.length;i++){
                dataSel.push(dataNew[i]);
                }
              }
              linechart(dataNew);
              console.log(dataNew);
          });

1 个答案:

答案 0 :(得分:1)

每次都会创建一个新图表,因为每次调用函数linechart()时,您都会在页面正文中附加一个新图形(svg元素)。

这是代码中的代码段,每次都附加一个新图表。

  // append the svg obgect to the body of the page
  // appends a 'group' element to 'svg'
  // moves the 'group' element to the top left margin
  var svg = d3.select("body").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("id","linechart")
      .attr("transform",
            "translate(" + margin.left + "," + margin.top + ")");

如果要更新同一图表,只需修改linechart()函数即可引用相同的svg元素。你可以通过为svg元素声明一个全局变量来实现这一点,并在你的linechart()方法中使用它,如下所示:

  // If graph is not there, create it
  if(!svg) {
      // append the svg object to the body of the page
      //appends a 'group' element to 'svg'
      // moves the 'group' element to the top left margin
      svg= d3.select("body").append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("id","linechart")
          .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");
  }

注意:将svg声明为全局变量(可能位于脚本标记的开头):

var svg;