d3 bar chart with sub categories

心已入冬 提交于 2019-12-24 16:44:05

问题


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.


回答1:


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 rects 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 the 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/



来源:https://stackoverflow.com/questions/16710014/d3-bar-chart-with-sub-categories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!