Search code examples
javascriptd3.jsaxis-labels

How can I control the date format for d3 scaleTime and remove unwanted clock time ticks?


I'm trying to display a week's worth of data in an area chart, and would like to use scaleTime() to populate my x axis. I've converted the date strings to date objects, and the domain appears to be correct, but I can't get the x axis to display the format I want. What I would like to see are 7 tick marks with the day, month, and year displayed. Instead, I'm seeing the day of the week and the date, and there are additional tick marks displaying '12 PM', as in the attached picture. enter image description here

I've tried specifying the number of tick marks, but then it gets even weirder, especially on month transitions, and might display something like 'Mon 29, Tues 30, Wed 31, November, Fri 2'.

Bottom line, am I missing something in how I'm implementing the scale, and if not, how might I go about fine-tuning the tick marks to only show what I want to see? The examples I've been able to find don't seem to run into the same problems I'm experiencing.

Current format of my date objects: "2020-07-22T06:00:00.000Z"

The code:

let x = d3.scaleTime().range([0, width-margin.right-margin.left])
let y = d3.scaleLinear().range([height-margin.bottom, margin.top])
x.domain([d3.min(area_data, d => d.date), d3.max(area_data, d=>d.date)])
y.domain([0, max_cases])
let xAxis = d3.axisBottom(x);
let yAxis = d3.axisLeft(y);

Thanks in advance.


Solution

  • You can do something like

    const xAxis = d3.axisBottom(x)
        .ticks(d3.timeDay.every(1), '%-d %b %Y');
    

    The first argument to ticks says that you want one tick for each day. The second argument is a format specifier that defines how to format the dates as strings. '%-d %b %Y' shows the day with no padding, the abbreviated month name, and the full year. For example, 22 Nov 2021. You can modify this as needed to get your desired format.