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.
以下是我的代码的相关部分.目前,这根本没有任何吸引力.
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);
Run Code Online (Sandbox Code Playgroud)
JSFiddle这里有完整的图表:http://jsfiddle.net/zNX8p/
明白了(我想):
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);
Run Code Online (Sandbox Code Playgroud)
datum不返回enter选择,因此您需要通过传递数据data。