Ben Foster
Ben Foster

Reputation: 34800

How to align ticks with bars in horizontal bar chart / row chart

I've created a horizontal bar chart / row chart and am struggling to vertically align the Y-axis ticks with the center of my bars.

To create the Y-axis I'm using the following code:

var yScale = d3.scale.ordinal()
  .domain(data.map(function (d) {
    return d.subject;
  }));
  .rangeRoundBands([0, height]);

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

And creating my bars like so:

  // Render the bars
  svg.selectAll('bar')
    .data(data)
    .enter()
    .append('rect')
    .attr('x', 1)
    .attr('y', function (d) {
      return yScale(d.subject);
    })
    .attr('width', function (d) {
      return xScale(d.value)
    })
    .attr('height', barHeight)
    .attr('fill', function (d, i) {
      return color(i);
    });

I'd like to be able to set the height of my chart to any value and have the ticks aligned correctly.

JSFiddle

Upvotes: 0

Views: 1538

Answers (1)

jshanley
jshanley

Reputation: 9128

The issue you are having is that you assigned an arbitrary barHeight value of 40 units.

When you use an ordinal scale with rangeRoundBands, d3 calculates a band size for you. You should use this value for your bar height. You can access the value that was calculated for your bands as ordinal.rangeBand, or in your specific case, yScale.rangeBand.

// instead of `barHeight`
.attr('height', yScale.rangeBand);

To avoid having all of your bars touching one another, you can give a second parameter to your rangeRoundBands method which is the padding between bands. Play around with the values for padding until you get the desired output.

Here's an updated JSFiddle

Upvotes: 2

Related Questions