Pieterjan
Pieterjan

Reputation: 475

Axis not ligning up to bars

I have this d3 code, but I'm having trouble to align the bars to the x-axis. I want the number, which represents an hour (range 0h-23h) to appear in the middle of the number of hours, which is the y-value.

The variable times gets instantiated with 24 values (indexes 0 to 23 h). Any response or ideas are welcome. What it looks like now;

https://i.sstatic.net/m1QOi.png

var times = buildTimeTable(data);
var margin = {top: 20, right: 10, bottom: 20, left: 10};
var width = 500- margin.left - margin.right, height = 200- margin.top - margin.bottom;
var x = d3.scale.linear().domain([0, 23]).range([0, width]);
var y = d3.scale.linear().domain([0, Math.max.apply(Math, times)]).range([height, 0]);
var xAxis = d3.svg.axis().orient("bottom").scale(x).ticks(24);
var yAxis = d3.svg.axis().orient("left").scale(y);
d3.select("#statistics-hours > svg").remove();
var svg = d3.select("#statistics-hours").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");;
var bar = svg.selectAll(".bar").data(times).enter().append("rect")
.attr("class", "bar")
.attr("width", (width)/times.length - 5)
.attr("height", function(d){return height - y(d);})
.attr("x", function(d, i){return i * (width/times.length);})
.attr("y", function(d){return y(d);})
.attr("fill", "steelblue");
svg.append("g").attr("class", "axis").attr("transform", "translate("+ margin.left +"," + (height) + ")").call(xAxis);
svg.append("g").attr("class", "axis").attr("transform", "translate(" + (margin.left) + ",0)").call(yAxis);

Upvotes: 0

Views: 40

Answers (1)

pylua
pylua

Reputation: 635

You probably want to consider using an ordinal scale.

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

Now, x is just

.attr('x',function(d){return x(d);})

And the width is just...

.attr('width',function(d){return x.rangeBand();})

Upvotes: 1

Related Questions