I have written a reusable d3 line chart (code below). Unfortunately it only updates properly when the data array passed to it is updated; if it is passed a new data array, it does not update at all - you can see it in this jsfiddle.
Here is the html, which is mostly the embedded demo calling script:
<style>
path { stroke: purple; stroke-width: 2px; fill: none; }
</style>
<body>
<div id="demo"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="demoChart.js"></script>
<script>
var chart = demoChart();
var pts = [[[0,0],[200,0.25],[500,1]]];
d3.select("#demo").datum(pts).call(chart);
setTimeout(function() {
console.log("Modifying data array");
pts[0][2][1] = 0.5;
d3.select("#demo").datum(pts).call(chart);
},1000);
setTimeout(function() {
console.log("Passing new data array");
d3.select("#demo").datum([[[0,1],[200,0.45],[500,0]]]).call(chart);
},2000);
</script>
You can see the second time it calls chart
it directly updates a single point in the data array (pts[0][3][1] = 0.5
), and the chart animates properly. The third time it passes a new data array, and the chart does not change.
Here is the demoChart.js
code (based on the reusable charts pattern):
function demoChart() {
function xs(d) { return xScale(d[0]) }
function ys(d) { return yScale(d[1]) }
var xScale = d3.scale.linear().domain([0, 500]).range([0, 400]),
yScale = d3.scale.linear().domain([0, 1]).range([400, 0]),
line = d3.svg.line().x(xs).y(ys);
function chart(selection) {
selection.each(function(data) {
console.log("passed data: ", data);
// Select the svg element, if it exists; otherwise create it
var svg = d3.select(this).selectAll("svg").data([1]);
var svgGEnter = svg.enter().append("svg").append("g");
// Select/create/remove plots for each y, with the data
var plots = svg.select("g").selectAll(".plot").data(data);
plots.exit().remove();
var plotsEnter = plots.enter().append("g").attr("class","plot");
plotsEnter.append("path");
// Update the line paths
plots.selectAll("path")
.transition()
.attr("d", function(d,i) {
console.log("transitioning line with data: ", d);
return line.apply(this, arguments);
});
svg.attr("width", 400).attr("height", 400);
});
}
return chart;
}
I suspect I am missing something fundamental about how d3 works.
How can I make the chart update properly when a new data array is passed?