How to handle layers with missing data points in d3.layout.stack()

后端 未结 3 1859
悲&欢浪女
悲&欢浪女 2021-02-04 00:47

I\'m using d3.stack to create a stacked area chart but I get an error if I have don\'t have an equal number of items in each layer. I\'m starting with an array of data like this

3条回答
  •  盖世英雄少女心
    2021-02-04 00:54

    This isn't d3 specific but rather a general solution for filling in the gaps in a array of keyed data. I modified your jsfiddle here with the following function:

    function assignDefaultValues( dataset )
    {
        var defaultValue = 0;
        var keys = [ 'Group1' , 'Group2', 'Group3' ];
        var hadData = [ true, true, true];
        var newData = [];
        var previousdate = new Date();
        var sortByDate = function(a,b){ return a.date > b.date ? 1 : -1; };
    
        dataset.sort(sortByDate);
        dataset.forEach(function(row){
            if(row.date.valueOf() !== previousdate.valueOf()){
                for(var i = 0 ; i < keys.length ; ++i){
                    if(hadData[i] === false){
                        newData.push( { key: keys[i], 
                                       value: defaultValue, 
                                       date: previousdate });
                    }
                    hadData[i] = false;
                }
                previousdate = row.date;
            }
            hadData[keys.indexOf(row.key)] = true; 
        });
        for( i = 0 ; i < keys.length ; ++i){
            if(hadData[i] === false){
                newData.push( { key: keys[i], value: defaultValue, 
                                date: previousdate });
            }
        }
        return dataset.concat(newData).sort(sortByDate);
    }
    

    It walks through the given dataset and, whenever it comes across a new date value, assigns a default value to any keys that have not yet been seen.

提交回复
热议问题