Skip to content Skip to sidebar Skip to footer

Flatten D3.js Nested Data Or Map It To New Dataset

Total noob to D3.js and working on creating my first grouped bar chart. However I'm having trouble making my data fit with the examples online. I am trying to use this example here

Solution 1:

It's not clear from the question if the aim is to group by state ("Texas", "Colorado"...) or date ("1/10/2014", "2/10/2014"...) along the x-axis.

Assuming date (because that's how the data is currently structured), here's a working plunk: http://plnkr.co/edit/C8lkPMGanFY9BkTc6f1i?p=preview

The code that processes the data into a format that your existing D3 code for grouped bar chart can handle looks like this:

// Call the first mapping function on every 'date' in the data array
processed_data = data.map( function (d) {
    var y0 = 0;
    var total = 0;
    return {
        date: d.key,
        // Call the second mapping function on every 'state' in the given date arrayvalues: (d.values).map( function (d) {
            return_object = {
                state: d.key,
                count: d.values,
                y0: y0,
                y1: y0 + d.values
            };
        // Calculate the updated y0 for each new state in a given date
        y0 = y0 + d.values;
        // Add the total for a given state to the sum total for that date
        total = total + d.values;
        return return_object;
        }),
        total: total
    };
});

We use nested array.map transforms to manipulate your two-level nested data into the expected format and calculate y0, y1 and total values. Your processed_data object will then look like this:

processed_data view in console

The only other tricky bit will be to calculate your list of unique states, in order to define the color.domain. If you don't want to hard-code this (e.g. because the list may vary from dataset to dataset, you could use this approach:

// Define the color domain, by first building a list of states:var states = [];
// Loop through each date
processed_data.forEach(
    function (d) {
        // Loop through each state in that date
        d.values.forEach(
            function(d) {
                // add to the array if not already presentif (!(states.indexOf(d.state) > -1)) {
                    states.push(d.state)
                }
            }
        ) 
    }
);
color.domain(states);

Post a Comment for "Flatten D3.js Nested Data Or Map It To New Dataset"