简体   繁体   English

使用新数据更新d3图表

[英]Making a d3 chart update with new data

I have an example of a chart on jsFiddle which has multiple groups of multiple lines. 在jsFiddle上有一个图表示例,该图表具有多组多行。 It draws successfully, but I would like to be able to transition to new sets of data. 它绘制成功,但是我希望能够过渡到新的数据集。

The example should update with new data after 4 seconds. 该示例应在4秒钟后使用新数据进行更新。 Although the chart gets called (and outputs something in the console), the lines aren't updated. 尽管图表被调用(并在控制台中输出一些内容),但线条不会更新。

I've tried lots of variations based on existing, simpler examples, with no luck. 我已经基于现有的简单示例尝试了很多变体,但是没有运气。 I suspect its the nested data based on this SO answer that's confusing me even more than usual. 我怀疑其基于此SO答案的嵌套数据比平时更让我感到困惑。

SO insists I have some code in the answer, so here's where I assume I need to add/change something: SO坚持我在答案中有一些代码,所以这是我假设需要添加/更改的地方:

  svg.transition().attr({ width: width, height: height });
  g.attr('transform', 'translate(' + margin.left +','+ margin.right + ')');

  var lines = g.selectAll("g.lines").data(function(d) { return d; });
  lines.enter().append("g").attr("class", "lines");

  lines.selectAll("path.line.imports")
      .data(function(d) { return [d.values]; })
      .enter().append("path").attr('class', 'line imports');

  lines.selectAll('path.line.imports')
      .data(function(d) { return [d.values]; })
      .transition()
      .attr("d", function(d) { return imports_line(d); });

  // repeated for path.line.exports with exports_line(d).

The problem is the way you're determining the top-level g element that everything is appended to: 问题是您确定将所有内容附加到的顶级g元素的方式:

var g = svg.enter().append('svg').append('g');

This will only be set if there is no SVG already, as you're only handling the enter selection. 仅当尚无SVG时才设置此设置,因为您仅在处理回车选择。 If it exists, g will be empty and therefore nothing will happen. 如果存在,则g将为空,因此将不会发生任何事情。 To fix, select the g explicitly afterwards: 要解决此问题,请在之后明确选择g

var g = svg.enter().append('svg').append('g').attr("class", "main");
g = svg.select("g.main");

Complete demo here . 在此处完成演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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