Reputation: 8080
Is it possible to have sub categories in a bar chart in d3? I don't think it's possible out of the box, but maybe someone has an idea of how to do it. An example would be sales of products (A, B, C) per month:
= =
= = =
= = = = =
= = = = = =
+-+-+-+-+-+-+-+-+- ...
| A B C | A B C | ...
| Jan | Feb | ...
I'm not sure how I would go about adding another dataset to a bar chart.
Upvotes: 2
Views: 1994
Reputation: 6192
Take each set of data you have, added it a list and then transpose the data.
var dataA = [1, 2, 3, 4, 5];
var dataB = [5, 4, 3, 2, 1];
var dataC = [5, 4, 3, 4, 5];
var dataAll = [dataA, dataB, dataC];
var dataT = d3.transpose(dataAll);
In D3.js this is not too difficult and the d3.transpose
will transposition of the data for you. The hardest part really is doing in such a way that is easy to read/update. Bind outer list to a g
object. I would use a transformation on this group to shift it to the right by the position in the list. Then when you are dealing with individual rect
s later you don't have to calculate the correct position of the month. This will also make labels much easier and as always good separations of concerns. You can then bind the inner list to rect
's and add a little color to give the chart shown above.
var chart = d3.selectAll('#chartArea')
.append('svg')
var month = chart.selectAll('g')
.data(dataT)
.enter()
.append('g')
.attr('transform', function(d,i){return 'translate(' + x(i) + ', 0)';});
month.selectAll('rect')
.data(function (d) {return d;})
.enter()
.append('rect')
.attr('x', function(d, i){return x(i/groups);})
.attr('y', function(d){return h-y(d);})
.attr('width', function(){return x(1/groups);})
.attr('height', function(d){return y(d);})
.attr('fill', function(d, i){return groupColor(i);})
A working example is on JSFiddle http://jsfiddle.net/hKvwa/
Upvotes: 2