d3 autospace overlapping tick labels

I've had a similar problem with multiple (sub-)axis, where the last tick overlaps my vertical axis in some situations (depending on the screen width), so I've just wrote a little function that compares the position of the end of the text label with the position of the next axis. This code is very specific to my use case, but could adapted easily to your needs:

var $svg = $('#svg');

// get the last tick of each of my sub-axis
$('.tick-axis').find('.tick:last-of-type').each(function() {

  // get position of the end of this text field
  var endOfTextField = $(this).offset().left + $(this).find('text').width();

  // get the next vertical axis
  var $nextAxis = $('line[data-axis="' + $(this).closest('.tick-axis').attr('data-axis') + '"]');

  // there is no axis on the very right, so just use the svg width
  var positionOfAxis = ($nextAxis.length > 0) ? $nextAxis.offset().left : $svg.offset().left + $svg.width();

  // hide the ugly ones!
  if (endOfTextField > positionOfAxis) {
    $(this).attr('class', 'tick hide');
  }

});

The ticks with color: aqua are the hidden ones:

enter image description here


There is no way of doing this automatically in D3. You can set the number of ticks or the tick values explicitly (see the documentation), but you'll have to figure out the respective numbers/values yourself. Another option would be to rotate the labels such that there is less chance of them overlapping.

Alternatively, like suggested in the other answer, you could try using a force layout to place the labels. To clarify, you would use the force layout on the labels only -- this is completely independent of the type of chart. I have done this in this example, which is slightly more relevant than the one linked in the other answer.

Note that if you go with the force layout solution, you don't have to animate the position of the labels. You could simply compute the force layout until it converges and then plot the labels.