Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js: draw simple, updatable line graph?

I'm trying to draw a simple line graph in D3, but having a few problems.

I want the graph to be dynamic - so when the data updates, I'd like the graph to transition to the new values. So I need to use D3 transitions somewhere in my code, and I can't find a good example of doing that with a line graph.

Here are the relevant parts of my code. At the moment, this isn't drawing anything at all.

var data = [
 {
  "air_produced": 0.660985, 
  "air_used": 0.342706, 
  "datestr": "2012-12-01 00:00:00", 
  "energy_used": 0.106402
 } ... ];
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S");
data.forEach(function(d) {
  d.date = parseDate.parse(d.datestr);
});

var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

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

// How to draw the line?
var linegraph = d3.select("path.line").datum(data);
line.transition().duration(1000).attr("d", line);
linegraph.enter().append("path")
    .attr("class", "line")
    .attr("d", line);

JSFiddle here with the full graph: http://jsfiddle.net/zNX8p/

like image 893
Richard Avatar asked Sep 17 '13 12:09

Richard


2 Answers

Got it (I think):

var linegraph = svg.selectAll("path.line").data([data], function(d) { return d.date; });

linegraph.transition().duration(1000).attr('d', line);

linegraph.enter().append("path")
    .attr("class", "line")
    .attr("d", line);

datum does not return an enter selection, so you need to pass the data via data instead.

like image 131
Richard Avatar answered Oct 27 '22 01:10

Richard


d3 has a general update pattern that you should use for this case.

The convention is to have two functions, one to setup the visualization, and another to take data and update the visualization.

The update function takes in the new data, binds it, updates the graph and then adds or removes objects as necessary.

Mike Bostock has a great 3 part series explaining this which you can find here: https://twitter.com/mbostock/status/252496768267333632

like image 24
Solomon Avatar answered Oct 27 '22 01:10

Solomon