D3实时折线图

时间:2017-03-08 06:07:01

标签: javascript d3.js

我是D3的新手,我想知道在数据发生变化时如何更新图表。这是我的图表的代码:

var data = [
  { time: new Date(2017, 3, 8, 20, 0, 0), value: 30 },
  { time: new Date(2017, 3, 8, 20, 15, 0), value: 25 },
  { time: new Date(2017, 3, 8, 20, 30, 0), value: 35 },
  { time: new Date(2017, 3, 8, 20, 45, 0), value: 15 },
  { time: new Date(2017, 3, 8, 21, 0, 0), value: 20 }
];

var margin = { top: 20, left: 50, bottom: 20, right: 20 };
var height = 200 - margin.top - margin.bottom;
var width = 600 - margin.left - margin.right;

var svg = d3.select("#chart").attr("width","100%").attr("height","100%");

var group = svg.append("g")
                    .attr("height", height)
                    .attr("width", width)
                    .attr("transform","translate("+margin.left+","+margin.top+")");

var x = d3.scaleTime()
          .domain(d3.extent(data, function(d){return d.time;}))
          .range([0, width]);

var y = d3.scaleLinear()
          .domain(d3.extent(data, function(d){return d.value;}))
          .range([height, 0]);

var points = group.append("g").attr("class", "points");

var line = d3.line()
              .x(function(d){ return x(d.time); })
              .y(function(d){ return y(d.value); });

// graph points
points.append("path")
          .attr("fill", "none")
          .attr("stroke", "blue")
          .attr("strok-width", "3")
          .attr("d", line(data));

// add x axis
group.append("g")
      .attr("class","axis x")
      .attr("transform","translate(0, "+height+")")
      .call(d3.axisBottom(x));

// add y axis
group.append("g")
      .attr("class","axis y")
      .call(d3.axisLeft(y));

// y axis label
group.append("text")
      .attr("transform","rotate(-90)")
      .attr("y", 0 - margin.left/1.5)
      .attr("x",0 - (height / 2))
      .style("text-anchor", "middle")
      .text("value");

// x axis label
group.append("text")
      .attr("transform","translate("+width/2+","+(height+margin.top+margin.bottom)+")")
      .style("text-anchor", "center")
      .text("time");

如何更新新数据,例如。 data.push({ time: new Date(2017, 3, 8, 21, 15, 0), value: 28 })图表会更新以反映新数据?我已经看过一些示例,例如herehere,但不清楚更新部分的工作原理。你的答案中的一点解释也会很好,这足以让我理解:)

0 个答案:

没有答案