d3带有子类别的条形图 [英] d3 bar chart with sub categories

查看:145
本文介绍了d3带有子类别的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在d3中的条形图中是否可以有子类别?我不认为这是可能的开箱,但也许有人有一个想法,如何做到这一点。一个例子是每月销售产品(A,B,C):

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.

推荐答案

获取每组数据,添加一个列表,然后转置数据。

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);

在D3.js中,这不是太难, d3.transpose 将为您转换数据。最难的部分真的是这样做的方式是容易阅读/更新。将外部列表绑定到 g 对象。我将使用这个组上的一个变换,将它向右移动列表中的位置。然后当你处理个人 rect 的时候,你不必计算该月的正确位置。这也将使标签更容易和一如既往的良好分离的关注。您可以将内部列表绑定到 rect ',并添加一点颜色以显示上面的图表。

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);})   

$ b b

一个工作示例是关于JSFiddle的 http://jsfiddle.net/hKvwa/

这篇关于d3带有子类别的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆