Created
August 10, 2017 12:41
-
-
Save peterbraden/254e7910e3a259cb8c0d2d076a3b9343 to your computer and use it in GitHub Desktop.
D3 Axis with overlap avoidance.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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