rafforaffo
rafforaffo

Reputation: 531

Group data by calendar month

I'm very new on Javascript and I'm trying to learn D3.

I've got a json file (or a csv) with the following structure:

[{"tot_b": "172", "tot_a": "91", "datetime": "2012-01-01"},
{"tot_b": "116", "tot_a": "69", "datetime": "2012-01-02"},
{"tot_b": "122", "tot_a": "88", "datetime": "2012-02-01"},
{"tot_b": "30", "tot_a": "116", "datetime": "2012-02-02"},
{"tot_b": "19", "tot_a": "99", "datetime": "2012-03-01"},
{"tot_b": "116", "tot_a": "84", "datetime": "2012-03-02"},]

Among others, the aim is to show a number of bar charts with the values of tot_a, tot_b and tot_b/tot_a.

How do I read the json file and have a data structure where I sum the data corresponding to dates in the same calendar month? For example I'd like something like:

{
    'data': ['2012-01', '2012-02', '2012-03'],
    'tot_a': [91+69, 88+116, 99+84],
    'tot_b': [172+116, 122+30, 19+116],
}

I've looked in SO, but I haven't find anything similar to this. Any reference would be appreciated.

Upvotes: 0

Views: 1862

Answers (1)

mdml
mdml

Reputation: 22882

d3.nest is your friend for summarizing your data like this.

First, rollup your data to get the totals for tot_a and tot_b:

var nested_data = d3.nest()
  .key(function(d) { return d.datetime.split('-').slice(0, 2).join('-'); })
  .sortKeys(d3.ascending)
  .rollup(function(leaves) {
      return {
        tot_b: d3.sum(leaves, function(d){ return d.tot_b }),
        tot_a: d3.sum(leaves, function(d){ return d.tot_a; })
      };
  })
  .entries(data);

Then, unwrap it into the data structure you specified:

var keys = nested_data.map(function(d){ return d.key; });
var bar_chart_data = {
    data: keys,
    tot_a: nested_data.map(function(d){ return d.values.tot_a; }),
    tot_b: nested_data.map(function(d){ return d.values.tot_b; })
};

And you get:

{
 "data":["2012-01","2012-02","2012-03"],
 "tot_a":[160,204,183],
 "tot_b":[288,152,135]
}

Here's a demo in a Fiddle.

Upvotes: 3

Related Questions