Reputation: 784
I am making a bar graph using D3 but when I plot the bar graph the x-ticks are not aligning under the bars. I think i'm not transforming the bars properly. I used the following example http://bost.ocks.org/mike/bar/
and I have been able to create the bar graph. Any help is appreciated. Thank You in advance.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [277, 407, 422, 279, 680, 485, 1624, 729, 327, 425, 205, 236];
var margin = {top: 30, right: 30, bottom: 30, left: 30},
width = 480 - margin.left - margin.right,
height = 340 - margin.top - margin.bottom;
var labels = [ {"key": "WS1"},{"key": "WS2"},{"key": "WS3"},{"key": "WS4"},
{"key": "WS5"},{"key": "WS6"},{"key": "WS7"},{"key": "WS8"},
{"key": "WS9"},{"key": "WS10"},{"key": "WS11"},{"key": "WS12"},
{"key": "WS13"}];
var colo = ['rgb(179,205,227)','rgb(140,150,198)','rgb(136,86,167)','rgb(129,15,124)',
'rgb(254,217,142)','rgb(254,153,41)','rgb(217,95,14)','rgb(153,52,4)',
'rgb(251,180,185)','rgb(247,104,161)','rgb(197,27,138)','rgb(122,1,119)']
var y = d3.scale.linear()
.domain([0, d3.max(data)])
.range([height, 0]);
var x = d3.scale.ordinal()
.domain(labels.map(function(d) { return d.key}))
.rangeRoundBands([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var chart = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g");
var barWidth = width / data.length;
console.log(width);
console.log(height);
console.log(data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g");
var ii = 0;
bar.append("rect")
.attr("fill", function(d) { ii += 1; return colo[ii-1]; })
.attr("y", function(d) { return y(d); })
.attr("x", function(d,i) { return x(d.key)})
.attr("width", barWidth - 1)
.attr("height", function(d) { return height - y(d); })
.attr("transform", function(d, i) {
return "translate(" + ((i) * (barWidth)) + ", 0)";
});
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height) + ")")
.call(xAxis);
</script>
Upvotes: 0
Views: 1406
Reputation: 527
Your labels
array has 13 items but your data
array has only 12. Make the lengths equal and your ticks will line up.
Upvotes: 1