Vivek
Vivek

Reputation: 4636

D3.js: Uniformly spaced bars on time scale

I am trying to create a simple bar chart with evenly spaced bars on time scale in x-axis but unsuccessful even with the solution given here

I am getting overlaps in the bars and unevenly spaced bars. Part of my code as below:

var x = d3.time.scale().range([width/data.length/2, width-width/data.length/2]);
var y = d3.scale.linear().range([height, 0]);

bars.transition().duration(1000)
    .attr("x", function(d) { return x(d.date) - Math.floor(width/data.length/2); })
    .attr("width", Math.floor(width / data.length))
    .attr("y", function(d) { return y(d.c); })
    .attr("height", function(d) { return height - y(d.c);});

bars.enter().append("rect")
    .attr("class", "air_used")
    .attr("width", Math.floor(width / data.length))
    .attr("x", function(d) { return x(d.date) - Math.floor((width/data.length)/2); })
    .attr("y", height)
    .attr("height", 0)
    .transition().duration(1000)
    .attr("y", function(d) { return y(d.c); })
    .attr("height", function(d) { return height - y(d.c);});

JSFiddle here: http://jsfiddle.net/vivekratnavel/v7rx8ku9/2/

Any help is appreciated. Thanks!

Upvotes: 1

Views: 621

Answers (1)

codex
codex

Reputation: 702

set hours to 0hrs:0min:0sec before scaling the time on x-axis.

http://jsfiddle.net/hnj30m4j/

bars.transition().duration(1000)
.attr("x", function(d) { return x(d.date.setHours(0,0,0))  - Math.floor(width/data.length/2); })
.attr("width", Math.floor(width / data.length))
.attr("y", function(d) { return y(d.c); })
.attr("height", function(d) { return height - y(d.c);});

bars.enter().append("rect")
.attr("class", "air_used")
.attr("width", Math.floor(width / data.length))
.attr("x", function(d) { return x(d.date.setHours(0,0,0)) - Math.floor((width/data.length)/2); })
.attr("y", height)
.attr("height", 0)
.transition().duration(1000)
.attr("y", function(d) { return y(d.c); })
.attr("height", function(d) { return height - y(d.c);});

Upvotes: 1

Related Questions