Javascript d3 更新数据和更新图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8538651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:25:52  来源:igfitidea点击:

d3 update data and update graph

javascriptd3.js

提问by Mike

I have the following simple line in d3 but haven't an issue trying to figure out how to pass it data2 and update the line to reflect the change.

我在 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>

回答by Derek Ekins

I am new to D3 but this is what I have found and I mainly figured this out from the sparklines example here.

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

Instead of drawing the line with this code:

而不是使用此代码绘制线条:

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

generate the line separately:

分别生成该行:

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

Then apply it to the data:

然后将其应用于数据:

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

Then when you want to update the data you call:

然后当你想更新你调用的数据时:

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

The sparklines example also shows you how to animate it :)

迷你图示例还向您展示了如何为其设置动画:)