D3.js time scale tick marks - Years and months only - Custom time format

Fiddle for SO

by k_sav

HTML

<div class="tl">
</div>

JavaScript

// Config SVG
var width = 500,
  height = 300,
  minDate = '1860',
  maxDate = '1958';

// Draw SVG element
var svgSelect = d3.select('div.tl').append('svg');

// Translate SVG G to accomodate margin
var translateGroupSelect = svgSelect
  .attr('width', width)
  .attr('height', height)
  .append('g');

// Define d3 xScale
var x = d3.time.scale()
  .domain([new Date(minDate), new Date(maxDate)])
  .range([0, width]);

// Define main d3 xAxis
var xAxis = d3.svg.axis()
  .scale(x)
  .ticks(10);

// Draw axes
var axes = translateGroupSelect.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + 0 + ")")
  .call(xAxis);

// Define zoom
var zoom = d3.behavior.zoom()
  .x(x)
  .scaleExtent([1, 32])
  .center([width / 2, height / 2])
  .size([width, height])
  .on("zoom", draw);


// Apply zoom behavior to SVG element
svgSelect.call(zoom);


// Repetitive drawing stuff on every zoom event
function draw() {
  xAxis.ticks(calcTickAmount());
  axes.call(xAxis);
}

function calcTickAmount() {
  if (d3.event.scale > 15) {
    return 3
  } else {
    return 10;
  }
}