6

I like to make this vertical Bar Chart (http://bl.ocks.org/mbostock/3886208) to a horizontal Bar Chart.

Thanks for your help!

Code examples would be nice.

Daniel Z
  • 63
  • 1
  • 5

1 Answers1

12

It's just a matter of reversing the domains, axis and then the rect calculations:

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); });

Here's the full working example.

Mark
  • 106,305
  • 20
  • 172
  • 230
  • I like to add two features: first: bar label inside the bars and second: x axis a time scale with this data input: State, int, ext AL,00:13:00,00:16:02 AK,00:20:03,0 AZ,00:58:52,0 AR,00:45:30,00:17:39 CA,0,00:54:08 CO,00:35:01,0 CT,0,00:03:39 – Daniel Z Aug 31 '15 at 09:35