blong824
blong824

Reputation: 4030

d3.js convert data using nest

I'm trying out d3.js for the first time and trying the stacked to grouped bars example.

My data is in the following format:

var data = [
  {"year":2015, values:[1,2,3]},
  {"year":2016, values:[10,20,30]},
  {"year":2017, values:[100,200,300]}
];

I would like the x-axis to be year and the y-axis to be the values.

I am having trouble determining which parts of the api to use. Do I use nest, map, or both?

I need the data to be graphed as value1 (1,10,100), value2 (2,20,200), and value3 (3,30,300)

Thanks

Upvotes: 0

Views: 73

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

Your data is like this

var data = [
  {"year":2015, values:[1,2,3]},
  {"year":2016, values:[10,20,30]},
  {"year":2017, values:[100,200,300]}
];

Need a paser to parse your date

 parse = d3.time.format("%Y").parse;

next group the data

//[0,1,2] index of the array so that the y can be calculated as d.values[grp]..here grp will be group which will have value 0 1 2
var newData = d3.layout.stack()([0,1,2].map(function(grp) {
    return data.map(function(d) {
      return {x: parse("" +d.year), y: +d.values[grp]};
    });
  }));

This will make the newData in the format you wish:

[[{"x":"2014-12-31T18:30:00.000Z","y":1,"y0":0},
{"x":"2015-12-31T18:30:00.000Z","y":10,"y0":0},
{"x":"2016-12-31T18:30:00.000Z","y":100,"y0":0}],
[{"x":"2014-12-31T18:30:00.000Z","y":2,"y0":1},
{"x":"2015-12-31T18:30:00.000Z","y":20,"y0":10},
{"x":"2016-12-31T18:30:00.000Z","y":200,"y0":100}],
[{"x":"2014-12-31T18:30:00.000Z","y":3,"y0":3},
{"x":"2015-12-31T18:30:00.000Z","y":30,"y0":30},
{"x":"2016-12-31T18:30:00.000Z","y":300,"y0":300}]]

Hope this helps!

Working sample here

Upvotes: 1

Related Questions