Horizontal bar chart y axis alignment

mawo

I have a problem with the yAxis in my horizontal bar chart.

var data = [0, 0, 0, 4, 0, 0, 0, 0, 18, 0, 0, 0, 52, 14, 0, 16];

var margin = { left: 20, top: 0  },
    width = 420,
    barHeight = 20,
    height = barHeight * data.length;

var xScale = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width - margin.left]);

var yScale = d3.scale.linear()
    .domain([0, data.length])
    .range([0, height]);

var chart = d3.select(".degree-hist")
    .attr("width", width)
    .attr("height", barHeight * data.length)
    .append("g")
    .attr("transform", function(d, i) { return "translate(" + margin.left + ", 0)"; });

var bar = chart.selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", xScale)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return xScale(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d > 0 ? d : ""; });

var yAxis = d3.svg.axis()
    .orient('left')
    .scale(yScale)
    .tickSize(2)
    .tickFormat(function(d, i){ return i + 1; })
    .tickValues(d3.range(data.length));

chart.append('g')
    .attr("transform", "translate(0,0)")
    .attr('id','yaxis')
    .call(yAxis);

I've illustrated the problem here: http://jsfiddle.net/mt556rot/3/

For some reason I did not manage to align the y-axis labels. I'd like to align the labels to the bar they belong to. In my example they appear on the upper edge of the bar, though. Also the ticks are not visible.

Any ideas how to fix this?

Mark

You are not centering the bars on the axis labels, they are starting on them:

bar.append("rect")
  .attr("width", xScale)
  .attr("height", barHeight - 1)
  .attr("y", -barHeight / 2); <-- added this to center

Also, your top tick label is being cut off because you didn't take into account the top margin:

var chart = d3.select(".degree-hist")
    .attr("width", width)
    .attr("height", barHeight * data.length + margin.top)
    .append("g")
    .attr("transform", function(d, i) { return "translate(" + margin.left + ", " + margin.top + ")"; }); // <-- margin.top into transform with top > 0

Finally, you didn't set any style for your ticks (CSS from here):

#yaxis path,
#yaxis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

Updated fiddle.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related