Reputation: 1930
I am trying out d3 ,started out with trying to create a bar chart.
This is what 've managed to do :
Notice how the ticks are not perfectly aligned with the bars ,
ideally I want to have them right under the bars ,centering them under each bar.
But I can't seem to control their location. Here is how I am adding them
//label array is an array of letter,correposding to a value in the original css file
var xScale = d3.scale.ordinal()
.domain(labelArray)
.range([0, width])
.rangeBands([0, width], 0.3);
var hGuide=d3.select('svg').append('g') ;
hAxis(hGuide);
hGuide.attr('transform','translate('+margin.left+','+(height+margin.top)+')');
And this is how I position the bars
canvas
.append('g')
.attr('transform', 'translate('+ margin.left +', '+ margin.top +')')
.selectAll('rect').data(bardata)
.enter().append('rect')
.style('fill', function(d,i) {
return colors(i);
})
.attr('width', xScale.rangeBand())
.attr('x', function(d,i) {
return (i*(width/labelArray.length));
})
.attr('height', 0)
.attr('y', height)
Don't seem to get my head around this ,
Here is the complete code on fiddle, the cross origin policy would mostly stop you from running the code.Although I thought it was helpful to describe it like this :https://jsfiddle.net/vhs1fwfp/
Upvotes: 1
Views: 88
Reputation: 32327
When you make the rectangles like this for the bar chart make use of the xScale instead doing like below.
selectAll('rect').data(bardata)
.enter().append('rect')
.style('fill', function(d,i) {
return colors(i);
})
.attr('width', xScale.rangeBand())
.attr('x', function(d,i) {//this is wrong
return (i*(width/labelArray.length));//remember variable i will be 0 @ the start of the loop that is why first bar starts with 0.
})
.attr('height', 0)
.attr('y', height)
So instead of doing this:
.attr('x', function(d,i) {
return (i*(width/labelArray.length));
})
do this:
.attr("x", function(d, i) { return xScale(labelArray[i]); })
Upvotes: 1