Add more grouping to grouped bar chart

时间:2017-11-13 06:48:10

标签: javascript d3.js bar-chart axes

I am making a grouped bar chart, for which the script is given at this link: https://jsfiddle.net/yL5z1q04/4/

Here I have groups of "salary" and "investment" for rank_buckets. Now, I want to add one more level of "grouping" on X-Axis based on "nation" key given in data.

My data is as follows:

 var data = [
    {group: "investment", height: 84636, rank_bucket: "a", nation: "United States"},
    {group: "salary", height: 76536, rank_bucket: "a", nation: "United States"},
    {group: "investment", height: 84636, rank_bucket: "a", nation: "Australia"},
    {group: "salary", height: 76536, rank_bucket: "a", nation: "Australia"},
    {group: "investment", height: 89626, rank_bucket: "b", nation: "Australia"},
    {group: "salary", height: 98234, rank_bucket: "b", nation: "Australia"},
    {group: "investment", height: 89626, rank_bucket: "b", nation: "United States"},
    {group: "salary", height: 98234, rank_bucket: "b", nation: "United States"}

   ];

The expected output should look somewhat like this:

enter image description here

How do I do this? I want to have "nation" information depicted on X-Axis along with rank_bucket.

Thanks!

1 个答案:

答案 0 :(得分:1)

您可以为rank_bucket,国家和群组创建多个scaleBand。

对于每个比例的范围宽度,使用前一比例的每个带宽()。例如,

var xscale_rank_bucket = d3.scaleBand()
          .rangeRound([0,width])
          .padding(0.2)
          .domain(Array.from(rank_buckets));

var xscale_nation = d3.scaleBand()
          .rangeRound([0,xscale_rank_bucket.bandwidth()])
          .padding(0.1)
          .domain(Array.from(nations));

你已经完成了一些,但只需要扩展到第三级。

此外,您可以为nation和rank_bucket创建多个x轴。对于国家轴,每个rank_bucket需要一个,因此您可以根据rank_bucket数据连接添加它们,例如:

var axisNationG = axes.selectAll(".axis-nation")
        .data(Array.from(rank_buckets))
      .enter()
      .append("g")
      .attr("transform", function(d){
        return "translate(" + xscale_rank_bucket(d) + ",0)"
      })
      .attr("class", "x axis")
      .call(axisNation)

轴可以翻译和设计,看起来像你的模拟。

https://jsfiddle.net/yL5z1q04/5/

PS - 更新的小提琴使用Sets来提取每个比例的唯一值,并将Sets转换为Arrays以用于比例和数据连接。