You could define a function to get the tickFormat
based on the dateDif
, so you wouldn't need to have such a large if-else block.
function getFormat() {
if (dateDif < 25) {
return d3.time.format('%H:%M');
} else {
return d3.time.format('%d/%m %H:%M');
}
}
Then you can set .ticks()
to a number. In the output, roughly that many ticks will be shown. d3 chooses a number of ticks that is close to your requested value, but also makes a few decisions to try to give optimal output.
// approximately 10 ticks will be displayed
xAxis = d3.svg.axis()
.scale(x)
.tickFormat(getFormat())
.ticks(10)
.orient("bottom");
If you use this method, you lose a little control over the exact number of ticks that will be shown, but you are guaranteed to have ticks displayed, and if you choose a sensible number for your ticks value, the output will probably be satisfactory.
Here's a fiddle using this technique with some contrived data.