How To Make Grouped Stacked Bar Chart In D3js?
I've the following d3 chart which is both grouped and each grouped contains a stacked bar. But somehow, I feel this is not a proper way to implement and little complicated. If ther
Solution 1:
You might need to have for ... in loops to build that object in your innerColumns like this:
itemLookup= data[0],
category = d3.keys(itemLookup.category),
items = d3.keys(itemLookup.category[type1[0]]),
columnHeaders = [],
innerColumns = (function(){
var result = {};
for(var i = 0, ii = category.length; i<ii; i++){
var holder = [];
for(var j = 0, jj = items.length; j<jj; j++){
columnHeaders.push(items[j]+'-'+category[i]);
holder.push(items[j]+'-'+category[i]);
result[category[i]] = holder;
}
}
return result;
})()...
You can refer to this for reference: https://jsfiddle.net/kyroskoh/tmec32z0/
Solution 2:
I have tried to achieve grouped stacked bar chart using d3.stack(). Here are 2 important parts of my solution:
var datasets=[d3.stack().keys(['type1','type3'])(data),
d3.stack().keys(['type2'])(data)];
var num_groups=datasets.length;
Here I am using .keys() method of d3.stack to create datasets for each group. After this we can use the code for creating stacked bar chart like this:
d3.range(num_groups).forEach(function(gnum) {
svg.selectAll('g.group'+gnum)
.data(datasets[gnum])
.enter()
.append('g')
.attr('fill',accent)
.attr('class', 'group'+gnum)
.selectAll('rect')
.data(d=>d)
.enter()
.append('rect')
.attr('x',(d,i)=>xscale(xlabels[i])+(xscale.bandwidth()/num_groups)*gnum)
.attr('y',d=>yscale(d[1]))
.attr('width',xscale.bandwidth()/num_groups)
.attr('height',d=>yscale(d[0])-yscale(d[1]));
});
You can see the complete solution here: https://jsfiddle.net/Abhi9kt/28wzdrfk/4/
Post a Comment for "How To Make Grouped Stacked Bar Chart In D3js?"