How to dynamically change the tick spacing of x-axis of a timeseries in chart.js when zooming enabled?

327 Views Asked by At

I have a chart that is based on 5-minute resolution data. If a user chooses to display 5 days worth of data, I want the x-axis to update from a "day" format like 'Jan 1' to more granular like format like "hour" and "minute" on zoom. I think I'm pretty close to figuring it out, I just can't figure out how to start my chart with the "day" format. Right now, it automatically chooses to start at "hour" and spaces the ticks closer together and as I zoom, it goes down to minute.

Currently, this is how my chart starts (there is data that shows, I just can't share it here): enter image description here

Ideally, I'd like my chart to start with just sparse day tick marks, like this: enter image description here

And as I zoom in, it'd work down to the hour, then the minute format which would display denser tick marks: enter image description here

I am using chartjs version 4.3.0.

//timeAxis is array of dates
timeAxis = [Fri Jan 01 2021 00:05:00, Fri Jan 01 2021 00:05:05, ..., Fri Jan 05 2021 24:00:00]
flowData = [{label: 00:05:00, value: 27}, {label: 00:05:05, value: 28}, ..., {label: 24:00:00, value: 32}]

const data = {
    //labels is the x-axis values
    labels: timeAxis,
    datasets: [
      {
        label: 'Total Plant Flow (Cubic Feet)',
        backgroundColor: dataAndModelsList[0].color,
        borderColor: 'black',
        data: flowData.map(({ value }) => value),
        yAxisID: 'y1'
      }
    ]
  }

const options: ChartOptions<'line'> = {
    responsive: true,
    maintainAspectRatio: true,
    aspectRatio: 2, 
    scales: {
      y1: {
        title: {
          display: true,
          text: 'Total Plant Flow (Cubic Feet)',
        },
        position: 'left'
      },
      x: {
        display: true,
        title: {
          display: true,
          text: 'Time'
        },
        type: 'timeseries',
        min: timeAxis[0].toString(),
        max: timeAxis.pop().toString(),
        time: {
          minUnit: 'minute',
          displayFormats: {
            //year: 'yyyy',
            //month: 'MMM',
            day: 'MMM dd',
            hour: 'MMM dd H:mm',
            minute: 'MMM dd H:mm:ss'
          }
        },
        ticks: {
          source: 'data'
        }
      }
    },
    plugins: {
      legend: {
        display: false,
        position: 'bottom',
        labels: {
          boxWidth: 0
        }
      },
      title: {
        display: true,
        text: 'Total Plant Flow at 5 Minute Intervals'
      },
      zoom: {
        zoom: {
          drag: {
            enabled: true
          },
          mode:'x'
        }
      }
    }
  }
0

There are 0 best solutions below