Reputation: 133
Say I have a csv file like this:
decade,year,cat1,cat2,cat3
1970,1971,2,3,6
1970,1972,3,8,4
1980,1981,5,8,7
1980,1982,9,2,4
1990,1991,7,9,5
1990,1992,9,5,6
I want to group the data by "decade", remove the "year column", and add the "cat" column. So the final array looks like this to use in a stacked bar chart:
decade,cat1,cat2,cat3
1970,5,11,10
1980,14,10,11
1990,16,14,11
Upvotes: 1
Views: 2040
Reputation: 3854
You can do it by using d3.nest
and d3.rollup
. We can nest by setting the decade as our key and then rolling/summing up the cat values based on the decade. The resulting key value pair will include the decade as the key and a values object with all 3 summed up cat values. Check snippet below:
var data = d3.csv.parse(d3.select('#data_csv').text());
var valuesByDecade;
data.forEach(function(d){
//group and organize your data as needed here
valuesByDecade = d3.nest()
//set the decade as your key
.key(function(d) {return d["decade"];})
//rollup and sum your cat values by decade
.rollup((function(d) {
return {
cat1: d3.sum(d, function(e) { return e["cat1"]; }),
cat2: d3.sum(d, function(e) { return e["cat2"]; }),
cat3: d3.sum(d, function(e) { return e["cat3"]; }),
};
}))
.entries(data);
});
console.log(valuesByDecade)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<pre id='data_csv'>decade,year,cat1,cat2,cat3
1970,1971,2,3,6
1970,1972,3,8,4
1980,1981,5,8,7
1980,1982,9,2,4
1990,1991,7,9,5
1990,1992,9,5,6
</pre>
Upvotes: 2