D3.js堆积条形图,从垂直到水平

时间:2015-08-30 16:40:19

标签: d3.js charts stacked-chart

我喜欢将此垂直条形图(http://bl.ocks.org/mbostock/3886208)制作成水平条形图。

感谢您的帮助!

代码示例会很好。

1 个答案:

答案 0 :(得分:12)

只需要反转域,轴和矩形计算:

var y = d3.scale.ordinal()
    .rangeRoundBands([height, 0], .1); // y becomes ordinal

var x = d3.scale.linear()
    .rangeRound([0, width]); // x becomes linear

// change state group to be positioned in the y now instead of x
var state = svg.selectAll(".state")
      .data(data)
      .enter().append("g")
      .attr("class", "g")
      .attr("transform", function(d) { return "translate(0," + y(d.State) + ")"; });

// rect calculations become
 state.selectAll("rect")
    .data(function(d) { return d.ages; })
    .enter().append("rect")
    .attr("height", y.rangeBand()) // height in now the rangeband
    .attr("x", function(d) { return x(d.y0); }) // this is the horizontal position in the stack
    .attr("width", function(d) { return x(d.y1) - x(d.y0); }) // this is the horizontal "height" of the bar
    .style("fill", function(d) { return color(d.name); });

这是完整的工作example