D3 time series example

Just a small example for time series illustrations with D3.

Time series data

The data for my time series example is a resampled and quantized record of a Wii Remote Plus controller with acceleration data of three axis. Here just the first ten lines of the 2426 lines long timeseries.csv file. Just the time and three integer values in every line separated by a space.

t x y z
0 -2 -3 6
1 -1 -3 6
2 -1 -3 6
3 -2 -5 7
4 -3 -5 7
5 -2 -4 7
6 -2 -4 8
7 -2 -4 9
8 -2 -5 10

Responsive SVG

The following styles are just to make the resulting SVG responsive.

#wrapper {
    position: relative;
    height: 0;
    width: 100%;
    padding: 0;
    /* padding-bottom will be overwritten by JavaScript later */
    padding-bottom: 100%;
}
#wrapper > svg {
    position: absolute;
    height: 100%;
    width: 100%;
    left: 0;
    top: 0;
}

Some HTML

All we need is a div element with id wrapper.

<div id="wrapper"></div>

Plotting the time series

We can fetch that data from the server, parse it and plot it into a responsive SVG with the following code.

var width = 10240,
    height = 1024,
    svg = d3.select("#wrapper")
        .attr("style", "padding-bottom: " + Math.ceil(height * 100 / width) + "%")
        .append("svg")
        .attr("viewBox", "0 0 " + width + " " + height);

var x = d3.scaleLinear().rangeRound([0, width]);
var y = d3.scaleLinear().rangeRound([height, 0]);

var spaceDsvParser = d3.dsvFormat(' ');
d3.request("/media/post/d3-time-series-example/timeseries.csv")
    .mimeType("text/csv")
    .response(function(xhr) { return spaceDsvParser.parse(xhr.responseText); })
    .get(function(error, data) {
        if (error) throw error;

        x.domain([0, data.length]);
        y.domain([-16, 16]);

        var drawAxis = function(yValueCallback, color) {
            svg.append('path')
                .datum(data)
                .attr("fill", "none")
                .attr("stroke", color)
                .attr("stroke-linejoin", "round")
                .attr("stroke-linecap", "round")
                .attr("stroke-width", 5)
                .attr("d", d3.line().x(function(d) { return x(d.t); }).y(yValueCallback));
        };
        drawAxis(function(d) { return y(d.x); }, "blue");
        drawAxis(function(d) { return y(d.y); }, "red");
        drawAxis(function(d) { return y(d.z); }, "green");
    });
Next Previous