0

I have implemented a realtime graph with javascript and d3.js. The data is generated randomly and it changes based on the random number. I want to fill the area under the line chart but I do not know how to fill it since the data is moving! The following code are correct for static charts but how I can use it for dynamic moving data

//Css part
.area {
fill: lightsteelblue;
stroke-width: 0;
}
//script 
var area = d3.svg.area()
.x(function(d, i) { return x(i); })
.y0(height)
.y1(function(d, i) { return y(d); });

svg.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area); 

And that is how my data is generated:

var n = 100,
    random = d3.random.normal(0, 50),
    data = d3.range(n).map(random);

Thanks,

Christopher Chiche
  • 15,075
  • 9
  • 59
  • 98
star
  • 317
  • 2
  • 6
  • 15

1 Answers1

1

In order to move the area in real time, you will have to do quite a bit of work. Fortunately Mike Bostock wrote a very good tutorial for path transitions with d3.js.

The key code is:

// push a new data point onto the back
data.push(random());

// redraw the line, and then slide it to the left
path
    .attr("d", area)
    .attr("transform", null)
    .transition()
    .ease("linear")
    .attr("transform", "translate(" + x(-1) + ")");
// pop the old data point off the front
data.shift();

Also note that you will certainly have to use selections at one point, to do so you can have a look at the following tutorial: A Bar Chart, Part 2.

Add to that the example of area chart that you already use and you are nearly done! The only difference is that you write

Now, you can also get inspiration from the following question: Smooth update to x axis in a D3 line chart?

Finally, here is a jsFiddle that provides you a working example of what you are looking for.

Community
  • 1
  • 1
Christopher Chiche
  • 15,075
  • 9
  • 59
  • 98