krazi
krazi

Reputation: 55

d3 bar chart - trying to line up tick to bar

I dont' have a whole lot of experience with D3 yet, but I found a post where the poster created a fiddle with this chart (which can be found here: Need help lining up x axis ticks with bars in D3.js bar chart). I was trying to modify it to to show days instead of months, but in doing so the alignment of the ticks is off. I was hoping I could get some help trying to align the ticks and understanding how this works.

http://jsfiddle.net/MmEjF/32/

I've added the ticks method to specify the steps, but in doing so it throws the alignment off.

var xAxis = d3.svg.axis().
scale(xTimeScale).
orient("bottom").
ticks(d3.time.days, 1).
tickFormat(formatDate);

Upvotes: 0

Views: 2875

Answers (1)

Christopher Chiche
Christopher Chiche

Reputation: 15345

You just have to change the following:

var xTimeScale = d3.time.scale().
domain([new Date(data[0].date), d3.time.day.offset(new Date(data[data.length - 1].date), 0)]).
range([0, width]); 

to:

var xTimeScale = d3.time.scale().
domain([new Date(data[0].date), d3.time.day.offset(new Date(data[data.length - 1].date), 1)]).
range([0, width]);

I just changed the last argument of offset to 1 instead of 0, with zero it just returns a copy of the date as explained in the documentation.

Moreover I would like to point that putting the . in the end of lines is not the convention and makes the code hard to read, I know that it comes from the previous example but don't get inspired by it. Here is how it should look like:

var xTimeScale = d3.time.scale()
    .domain([new Date(data[0].date), d3.time.day.offset(new Date(data[data.length - 1].date), 1)])
    .range([0, width]);

Here is the jsFiddle with the working code: http://jsfiddle.net/chrisJamesC/MmEjF/34/

Upvotes: 2

Related Questions