d3.js使用nest转换数据

时间:2015-11-09 20:52:32

标签: javascript d3.js

我是第一次尝试d3.js并尝试堆叠到分组的条形图。

我的数据采用以下格式:

textareas[i].style.cssText='height: 100px !important';

我希望x轴为年,y轴为值。

我无法确定要使用的api的哪些部分。我是否使用嵌套,地图或两者兼而有之?

我需要将数据绘制为value1(1,10,100),value2(2,20,200)和value3(3,30,300)

由于

1 个答案:

答案 0 :(得分:1)

您的数据是这样的

var data = [
  {"year":2015, values:[1,2,3]},
  {"year":2016, values:[10,20,30]},
  {"year":2017, values:[100,200,300]}
];

需要paser来解析您的日期

 parse = d3.time.format("%Y").parse;

下一组数据

//[0,1,2] index of the array so that the y can be calculated as d.values[grp]..here grp will be group which will have value 0 1 2
var newData = d3.layout.stack()([0,1,2].map(function(grp) {
    return data.map(function(d) {
      return {x: parse("" +d.year), y: +d.values[grp]};
    });
  }));

这将使newData以您希望的格式生成:

[[{"x":"2014-12-31T18:30:00.000Z","y":1,"y0":0},
{"x":"2015-12-31T18:30:00.000Z","y":10,"y0":0},
{"x":"2016-12-31T18:30:00.000Z","y":100,"y0":0}],
[{"x":"2014-12-31T18:30:00.000Z","y":2,"y0":1},
{"x":"2015-12-31T18:30:00.000Z","y":20,"y0":10},
{"x":"2016-12-31T18:30:00.000Z","y":200,"y0":100}],
[{"x":"2014-12-31T18:30:00.000Z","y":3,"y0":3},
{"x":"2015-12-31T18:30:00.000Z","y":30,"y0":30},
{"x":"2016-12-31T18:30:00.000Z","y":300,"y0":300}]]

希望这有帮助!

工作样本here