D3.js: draw a simple, updated graph?

I am trying to make a simple line graph in D3, but have a few problems.

I want the graph to be dynamic, so when the data is updated, I would like the graph to move to the new values. Therefore, I need to use D3 transitions somewhere in my code, and I cannot find a good example of this with a line graph.

Here are the relevant parts of my code. This is not drawing anything at the moment.

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 schedule: http://jsfiddle.net/zNX8p/

+7
javascript
source share
2 answers

Got (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 choice, so you need to pass data through data .

+1
source share

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

The agreement is to have two functions: one for customizing the visualization, and the other for collecting data and updating the visualization.

The update function accepts new data, connects it, updates the schedule, and then adds or removes objects as needed.

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

+1
source share

All Articles