D3

时间:2015-10-27 02:40:54

标签: javascript d3.js data-visualization

我正在尝试从堆叠在一起的多维数组渲染堆积条形图,我无法弄清楚如何配置每个矩形的y和高度值。我一直关注的教程是here,但他们的数据结构与我的差异很大。我相信解决方案是如何确定y0和y1值,但在D3中是一个新手我无法辨别它是如何在教程中计算的。

这是我到目前为止所做的事情(数据和legendLabels变量的返回数据位于顶部:

data = [["Privés dans les trois dimensions","30.2"],["Privés dans une dimension additionelle","24.4"],["Privés seulement dans la dimension spécifiée","8.32"],["Privés dans les trois dimensions","30.2"],["Privés dans une dimension additionelle","26.1"],["Privés seulement dans la dimension spécifiée","3.75"],["Privés dans les trois dimensions","30.2"],["Privés dans une dimension additionelle","33.1"],["Privés seulement dans la dimension spécifiée","10.4"]]

legendLabels = ["Nutrition","Santé","Eau"];


var $chart = $(chart),
    data = $chart.data("chartDataTest"),
    legendLabels = $chart.data("chartLabels"),
    groupedData = [];

$.each(legendLabels, function(i){
  var labelLength = legendLabels.length,
      dataLength = data.length;

  var sliceBeginning = i * labelLength,
      sliceEnd = sliceBeginning + labelLength;
      dataRange = data.slice(sliceBeginning, sliceEnd);

  groupedData.push(dataRange);
});

var yValues = [];

$.each(groupedData, function(i, dataGroup){
  var subGroupY = 0;
  $.each(dataGroup, function(ii, dataSubGroup){
    subGroupY += +dataSubGroup[1];
  });
  yValues.push(subGroupY);
});

var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var x0 = d3.scale.ordinal()
    .rangeRoundBands([0, width], 0.1);

var y = d3.scale.linear()
    .rangeRound([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format(".2s"));

var svg = d3.select(chart).append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("class", "parent-group")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

x.domain(legendLabels.map(function(d) { return d; }));
x0.domain(groupedData.map(function(d) { return d; }));
y.domain([0, d3.max(yValues, function(d) { return d; })]);

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

var group = svg
  .selectAll(".group")
  .data(groupedData)
  .enter()
  .append("g")
  .attr("class", "g")
  .attr("transform", function(d) {
    return "translate(" + x0(d) + ",0)";
  });

var yPosition = 0;

group
  .selectAll(".group")
  .data(function(d) { return d; })
  .enter()
  .append("rect")
  .attr("width", x.rangeBand())
  .attr("y", function(d, i) {
    return y(d[1]);
  })
  .attr("height", function(d) {
    return y(d[1]);
  });

这是我的图表到目前为止的样子:

enter image description here

1 个答案:

答案 0 :(得分:0)

Per @ CoolBlue的建议,我重新考虑使用d3的stack功能。我的新方法基于this tutorial。这是更新后的代码:

var $chart = $(chart),
    data = $chart.data("chartDataTest"),
    chartStacks = $chart.data("chartLabels"),
    groupedData = [],
    colors = [];


var width = 900,
    height = 500,
    margin = { top: 10, right: 50, bottom: 30, left: 50},
    x = d3.scale.ordinal().rangeRoundBands([0, width - margin.left - margin.right]),
    x0 = d3.scale.ordinal().rangeRoundBands([0, width - margin.left - margin.right], 0.1),
    y = d3.scale.linear().range([0, height - margin.top - margin.bottom]);
    y0 = d3.scale.linear().range([height - margin.top - margin.bottom, 0]);


var xAxis = d3.svg.axis()
      .scale(x0)
      .orient("bottom"),
    yAxis = d3.svg.axis()
      .scale(y0)
      .orient("left")
      .tickFormat(d3.format(".2s"));


$.each(chartStacks, function(i){
  var labelLength = chartStacks.length,
      dataLength = data.length;

  var sliceBeginning = i,
      dataRange = data.slice(sliceBeginning);

  colorGroup = [];

  $.each(dataRange, function(ii, colorData){

    if ( ii % labelLength == 0) {
      colorGroup.push(colorData[1]);
    }
  });

  var remappedValues = colorGroup.map(function(dat, i) {
      return {
        x: i,
        y: +dat
      }
  });

  var remappedColors = dataRange.map(function(dat, i) {
      return dat[0];
  });

  colors.push(remappedColors[0]);
  groupedData.push(remappedValues);
});

var stacked = d3.layout.stack()(groupedData);

x0.domain(chartStacks.map(function(d) { return d; }));
x.domain(stacked[0].map(function(d) { return d.x; }));
y.domain([0, d3.max(stacked[stacked.length - 1], function(d) { return d.y0 + d.y; })]);
y0.domain([0, d3.max(data, function(d) { return 90; })]);

var svg = d3.select(chart).append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);


svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(" + margin.left + "," + height + ")")
    .call(xAxis);

svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + margin.left + ", " + 46 + ")")
    .call(yAxis);

var svgContent = svg
  .append("g")
    .attr("class", "parent-group")
    .attr("transform", "translate(" + margin.left + "," + height + ")");

var valGroup = svgContent
  .selectAll(".parent-group")
  .data(stacked)
  .enter()
  .append("g")
  .attr("class", "valgroup");

var rect = valGroup.selectAll("rect")
  .data(function(d){return d;})
  .enter().append("svg:rect")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) { return -y(d.y0) - y(d.y); })
  .attr("height", function(d) { return y(d.y); })
  .attr("width", x.rangeBand() - 15);