Skip to content

Instantly share code, notes, and snippets.

@peterbraden
Created August 10, 2017 12:41
Show Gist options
  • Save peterbraden/254e7910e3a259cb8c0d2d076a3b9343 to your computer and use it in GitHub Desktop.
Save peterbraden/254e7910e3a259cb8c0d2d076a3b9343 to your computer and use it in GitHub Desktop.
D3 Axis with overlap avoidance.
var renderAxis = (axis, axelem, maxWidth) => {
var paint = function(x){
axis.ticks(x)
axelem.call(axis)
var width = d3.max(
d3.selectAll('.axes .tick')
.nodes()
.map( (x) => x.getBBox().width))
return (width * x < maxWidth)
}
var render = function(){
var x = 1
while(paint(++x)){}
paint(--x)
}
render()
}
var WIDTH = 500, HEIGHT = 100
var svg = d3.select('.el').append('svg')
.attr('width', WIDTH)
.attr('height', HEIGHT)
var x = d3.scaleTime()
.domain([new Date('2009-01-01'), new Date('2009-01-06')])
.range([0, WIDTH])
var axis = d3.axisTop(x)
var axelem = svg.append('g')
.attr('transform', 'translate(50,50)')
.attr('class', 'axes')
renderAxis(axis, axelem, WIDTH)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment