Skip to content

Instantly share code, notes, and snippets.

@tomshanley
Last active Feb 13, 2020
Embed
What would you like to do?
fresh block
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
.domain {
opacity: 0;
}
text {
text-anchor: middle;
}
</style>
</head>
<body>
<script>
console.clear()
let ticks1 = [ 1, 2, 3, 4, 5, 6, 7]
let ticks2 = [21, 22, 23, 24, 25, 16, ]
let width = 500
let axisWidth = 500
let margin = 50
let format = d3.format(",.0f")
let xScale = d3.scaleLinear()
.domain(d3.extent(ticks1))
.range([0, axisWidth])
let step = xScale(ticks1[1])
let xAxis = d3.axisBottom(xScale)
.tickValues(ticks1)
.tickFormat(format)
var svg = d3.select("body").append("svg")
.attr("width", width + margin + margin)
.attr("height", margin + margin)
let axes = svg.append("g")
.attr("transform", "translate(" + margin + ", " + margin + ")")
let xAxisG = axes.append("g")
.attr("transform", axisTranslate(ticks1))
let ticks = xAxisG.selectAll(".tick")
.data(ticks1, d => d)
.enter()
.append("g")
.attr("class", "tick")
.attr("transform", tickTranslate)
ticks.append("text")
.text(d => d)
updateAxis(ticks1, ticks2)
function updateAxis(currentTicks, newTicks){
// increase the number of ticks
let extentAllTicks = d3.extent(currentTicks.concat(newTicks))
let extentNewTicks = d3.extent(newTicks)
let intermediateTicks = d3.range(extentAllTicks[0], extentAllTicks[1] + 1)
axisWidth = (intermediateTicks.length - 1) * step
console.log(intermediateTicks)
ticks = xAxisG.selectAll(".tick")
.data(intermediateTicks, d => d)
.join("g")
.attr("class", "tick")
.attr("transform", tickTranslate)
ticks.append("text")
.text(d => d)
step = width/(newTicks.length - 1)
axisWidth = step * (intermediateTicks.length - 1)
xScale
.domain(extentNewTicks)
.range([0, width])
ticks.transition()
.duration(5000)
.attr("transform", tickTranslate)
ticks.selectAll('text')
.transition()
.duration(5000)
.style("opacity", function(d){
return (d >= extentNewTicks[0] && d <= extentNewTicks[1]) ? 1 : 0
})
}
function tickTranslate(d){
return "translate(" + xScale(d) + ",0)"
}
function axisTranslate(data){
return "translate(" + xScale(data[0]) + ",0)"
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment