d3.js: Align text labels between ticks on the axis

oluckyman picture oluckyman · Jul 9, 2013 · Viewed 20.2k times · Source

Is there an easy way to align text labels between ticks?

Here is my time axis with labels above the ticks:
enter image description here

I would like to place these labels like here:
enter image description here

Answer

oluckyman picture oluckyman · Jul 13, 2013

I ended up with one of the Lars Kotthoff's advices.

Every time when I call(axis) I also adjust text labels.
Here is simplified code:

function renderAxis() {
    axisContainer
        .transition().duration(300)
        .call(axis)                  // draw the standart d3 axis
        .call(adjustTextLabels);     // adjusts text labels on the axis 
}

function adjustTextLabels(selection) {
    selection.selectAll('.major text')
        .attr('transform', 'translate(' + daysToPixels(1) / 2 + ',0)');
}

// calculate the width of the days in the timeScale
function daysToPixels(days, timeScale) {
    var d1 = new Date();
    timeScale || (timeScale = Global.timeScale);
    return timeScale(d3.time.day.offset(d1, days)) - timeScale(d1);
}

Update:
BTW, here is a calendar demo with I ended up: http://bl.ocks.org/oluckyman/6199145

enter image description here