Reputation: 8645
I have a pretty simple line graph that is rendered by the code below. I have created a simple timer to push items into the data array and then redraw the graph. The problem is that the graph is not being redrawn. I can see that the line function is called every 1.5 seconds as expected, but the graph is just not redrawing.
I have tried a number of different things, and have tried to follow some of the answers to previous questions similar to this on SO, but I'm just stuck.
var data = getData();
var graph;
var line;
function getData() {
var arr = [];
for (var x = 0; x < 30; x++) {
arr.push(rand(100));
}
return arr;
}
function rand(max) {
return Math.floor(Math.random() * (max + 1))
}
setInterval(function() {
data.shift();
data.push(rand(100));
redraw();
}, 1500);
function redraw() {
graph.select("svg path")
.data([data])
.attr("d", line);
}
var m = [80, 80, 80, 80]; // margins
var w = 1000 - m[1] - m[3]; // width
var h = 400 - m[0] - m[2]; // height
var x = d3.scale.linear().domain([0, data.length]).range([0, w]);
var y = d3.scale.linear().domain([0, d3.max(data)]).range([h, 0]);
line = d3.svg.line()
.x(function(d,i) { return x(i); })
.y(function(d) { return y(d); })
graph = d3.select("#graph").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
var xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(true);
graph.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
var yAxisLeft = d3.svg.axis().scale(y).ticks(4).orient("left");
graph.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(-25,0)")
.call(yAxisLeft);
graph.append("svg:path")
.data([data])
.attr("d", line);
Upvotes: 1
Views: 955
Reputation: 51839
The problem is that your selector "svg path" isn’t specific enough: it matches the domain path drawn by your axes. You can fix that in one of two ways. You can either save a reference to the line path when you add it:
var path = graph.append("path")
.datum(data)
.attr("d", line);
Or you could assign it a specific class ("line") and then use a more specific selector (".line"). This will make it easier to style, as well.
graph.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
Upvotes: 2