使用新数据更新d3图表 [英] Making a d3 chart update with new data

查看:178
本文介绍了使用新数据更新d3图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 jsFiddle图表的示例,其中包含多个组的多行。它成功绘制,但我想能够转换到新的数据集。

I have an example of a chart on jsFiddle which has multiple groups of multiple lines. It draws successfully, but I would like to be able to transition to new sets of data.

示例应该在4秒后更新为新数据。

The example should update with new data after 4 seconds. Although the chart gets called (and outputs something in the console), the lines aren't updated.

我已经尝试了很多基于现有的简单示例的变体,没有运气。我怀疑其嵌套数据基于此SO

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:

  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).


推荐答案

问题是, -level g 所有内容附加到的元素:

The problem is the way you're determining the top-level g element that everything is appended to:

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

只有在没有SVG时才会设置,因为你只处理输入选择。如果存在, g 将为空,因此不会发生任何事。要修复,请事后显式选择 g

This will only be set if there is no SVG already, as you're only handling the enter selection. If it exists, g will be empty and therefore nothing will happen. To fix, select the g explicitly afterwards:

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

完成演示此处

这篇关于使用新数据更新d3图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆