Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
How to center label for time scale axis in D3.js?

How can I center the label so that it stays on zoom for the d3.scaleTime()?

Example

const scaleX = d3.scaleTime()
  .domain([
    min,
    max
  ])
  .range([0, width - paddings.left - paddings.right])
  .nice()
    
const periodLength = max.getFullYear() - min.getFullYear() // in years
const quaters = {
  0: 'I',
  3: 'II',
  6: 'III',
  9: 'IV'
}
const getLabelFormat = d => {
  if (periodLength > 2) {
    return d.getFullYear()
  } else {
    return `${d.getFullYear()} - ${quaters[d.getMonth()]}`
  }
}

let tickFrequency = [10]
if (periodLength < 10) {
  if (periodLength > 2) {
    tickFrequency = [d3.timeYear.every(1)]
  } else {
    tickFrequency = [d3.timeMonth.every(3)]
  }
}

const axisX = d3.axisBottom(scaleX)
  .tickArguments(tickFrequency)
  .tickFormat(getLabelFormat)

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!