javascriptcsvd3.jsstream-graph

streamgraph from .csv file in D3


I want to build a stream graph from data in a .csv file. I forked http://bl.ocks.org/lgrammel/1935509 to generate the stream graph, but I got stuck loading the data. My JS is below.

    var n = 8, // number of layers
    m = 54; // number of samples per layer

var colors = d3.range(n).map(function() { return d3.interpolateRgb("#aad", "#556")(Math.random()); });

var streamgraph = streamgraphChart()
        .margin({top: 10, right: 10, bottom: 10, left: 10})
        .color(function(d, i) { return colors[i]; }) // use same colors for both data sets
        .transitionDuration(1500);
d3.text("weekly_hours.csv", function(text) {
    var data = d3.csv.parseRows(text).map(function(row) {
        return row.map(function(value) {
          return +value;
        });
    });
    console.log(data);
    d3.select("#chart")
            .datum(data)
            .call(streamgraph);
  });

The console log shows the data array nicely, but I also get an error Error: Problem parsing d="MNaN,NaNLNaN,NaNLNaN,NaNLNaN,NaNLNaN,N. Nothing shows up at http://bl.ocks.org/korenmiklos/8052011


Solution

  • You have to provide data in a form which is amenable to the stack layout for the function to work as expected:

        by default the following attributes are required on each value:
    
        * x - the x-position of the value.
        * y - the y-thickness of the value.
        * y0 - the minimum y-position of the value (baseline).
    

    So you need to transform your data a bit more:

    var data = [];
    d3.csv.parseRows(text).forEach(function(row, idx) {
        row.forEach(function(value, layer) {
          if (typeof data[layer] === 'undefined') data[layer] = [];
          data[layer].push({ x : idx, y : +value });
        });
    });
    

    Working demo: http://plnkr.co/edit/P8Q4UGNpdUMw1V824vlK?p=preview