const x_scale_time = d3.scaleTime()
.domain([new Date(2017,12,1),new Date()])
.range([0, 960]);
const x_axis_time = d3.axisBottom()
.scale(x_scale_time)
.ticks(d3.timeMonth.every(1))
const x_scale_pow = d3.scalePow().exponent(2)
.domain([0,20000])
.range([0, 960]);
const x_axis_pow = d3.axisBottom()
.scale(x_scale_pow)
.ticks(10)
// ticksDistance is constant for a specific x_scale
const getTicksDistance = (scale) => {
const ticks = scale.ticks();
const spaces = []
for(let i=0; i < ticks.length - 1; i++){
spaces.push(scale(ticks[i+1]) - scale(ticks[i]))
}
return spaces;
};
//you have to recalculate when x_scale or ticks change
const ticksSpacingTime = getTicksDistance(x_scale_time);
const ticksSpacingPow = getTicksDistance(x_scale_pow);
const svg = d3.select("body").append("svg")
.attr("width", "500px")
.attr("height","350px")
.style("width", "100%")
.style("height", "auto");
// normal
svg.append("g")
.attr("class", "x-axis-time")
.attr("transform", "translate(0,0)")
.call(x_axis_time)
// shift labels to half of the ticks distance
svg.append("g")
.attr("class", "x-axis-time-shifted")
.attr("transform", "translate(0,40)")
.call(x_axis_time)
.selectAll("text")
.attr("x", (d,i) => ticksSpacingTime[i]/2)
// normal
svg.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0,110)")
.call(x_axis_pow)
// shift labels to half of the ticks distance
svg.append("g")
.attr("class", "x-axis-shifted")
.attr("transform", "translate(0,150)")
.call(x_axis_pow)
.selectAll("text")
.attr("x", (d,i) => ticksSpacingPow[i]/2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>