【问题标题】:d3 update data and update graphd3更新数据和更新图
【发布时间】:2012-01-22 05:52:08
【问题描述】:

我在 d3 中有以下简单行,但尝试弄清楚如何传递 data2 并更新行以反映更改没有问题。

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>D3 Line Chart Demo</title>
    <meta charset="utf-8" />    
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link rel="stylesheet" type="text/css" href="style.css">

    <script src="jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="d3.min.js" type="text/javascript" charset="utf-8"></script>
  <body>
    <button class="first last" onclick="transition()">
        Update
      </button>
    <div id="chart"></div>
  </body>

  <script>

    var data = [3, 7, 9, 1, 4, 6, 8, 2, 5];
    var data2 = [3, 7, 9, 1, 4, 6, 8, 2, 15];
    var width = 600;
    var height = 400;
    var max = d3.max(data);

    x = d3.scale.linear().domain([0, data.length - 1]).range([0, width]);
    y = d3.scale.linear().domain([0, max]).range([height, 0]);

    vis = d3.select('#chart')
        .style('margin', '20px auto')
        .style('width', "" + width + "px")
        .append('svg:svg')
        .attr('width', width)
        .attr('height', height)
        .attr('class', 'viz')
        .append('svg:g');

    vis.selectAll('path.line')
        .data([data])
        .enter()
        .append("svg:path")
        .attr("d", d3.svg.line().x(function(d, i) {
          return x(i);
        })
        .y(y));
  </script>
</html>

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    我是 D3 的新手,但这是我发现的,我主要是从迷你图示例 here 中发现的。

    不要用这段代码画线:

    vis.selectAll('path.line')
        .data([data])
        .enter()
        .append("svg:path")
        .attr("d", d3.svg.line().x(function(d, i) {return x(i); }).y(y));
    

    单独生成行:

     var line = d3.svg.line().x(function(d, i) { return x(i); }).y(y)
    

    然后将其应用于数据:

    vis.selectAll('path.line')
        .data([data])
        .enter()
        .append("svg:path")
        .attr("d", line);
    

    那么当你想更新你调用的数据时:

     vis.selectAll("path")
       .data([data]) // set the new data
       .attr("d", line); // apply the new data values
    

    迷你图示例还向您展示了如何对其进行动画处理:)

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      相关资源
      最近更新 更多