D3具有不同堆叠级别的堆叠条形图 [英] D3 Stacked bar chart with different stack level

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

问题描述

是否可以在D3中构建具有不同堆叠级别的堆叠条形图?

Is it possible to build a stacked bar chart in D3 with different stacked levels?

我一直在阅读有关内容,但是cud只找到具有相同堆叠级别的示例.

I've been reading about it but cud only find examples which has same stacked levels.

换句话说, 代替此JSON-

In other words, Instead of this JSON -

var layers = [
      {
        "name": "apples",
        "values": [
            { "x": 0, "y": 11},
            { "x": 1, "y": 10},
            { "x": 2, "y": 10}
        ]
      },
      {  
        "name": "oranges",
        "values": [
          { "x": 0, "y": 9},
          { "x": 1, "y": 9},
          { "x": 2, "y": 9}
        ]
      }
    ];

我们可以用-

var layers = [
      {
        "name": "apples",
        "values": [
            { "x": 0, "y": 11},
            { "x": 1, "y": 10},
            { "x": 2, "y": 10}
        ]
      },
      {  
        "name": "oranges",
        "values": [
          { "x": 0, "y": 9}
        ]
      }
    ];

我读了- https://bl.ocks.org/mbostock/3886208

https://bl.ocks.org/mbostock/1134768

https://github.com/mbostock/d3/wiki/Stack-Layout

推荐答案

这非常容易做到,具体取决于您如何设计将数据加载到图表中的方式.

This is fairly easy to do, depending on how you design your loading of data into the chart.

基本上,该过程将是:

  1. 在图层变量中使用data()函数,这样您便可以分别处理每个数据集
  2. 使用步骤1结果的enter()函数添加g元素
  3. 再次调用data(),这一次使用附加数据(.data(function(d){return d.values;}))的values
  4. 使用步骤3的结果的enter()函数生成条形图
  1. Use the data() function with the layers variable, which allows you to then work with each data set individually
  2. Add a g element using the enter() function of the result of step 1
  3. Call data() again, this time using the values of the attached data (.data(function(d){return d.values;}))
  4. Use the enter() function of the result of step 3 to generate the bars

请注意,要使内容实际堆叠,您需要跟踪每个x位置的当前堆叠高度.您要做的就是生成一个零数组,并在设置矩形的y属性时更新索引d.x处的值.

Note that to get things to actually stack you will need to keep track of the current stacked height of each x position. All you have to do is generate an array of zeroes and update the value at index d.x when setting the rectangle's y attribute.

小提琴显示了一个快速示例.为了使它成为一个可以正常工作的示例,您必须添加轴/比例和所有其他内容.

Fiddle showing a quick sample. To make this a fully working example, you'll have to add axes/scales and all the extra things.

这篇关于D3具有不同堆叠级别的堆叠条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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