Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the label and grid line position on a timeseries chart in Chart.js 3?

I'm upgrading from Chart.js 2 to 3 and encountering problems with my time chart.
Here's the fiddle: https://jsfiddle.net/58L42w3u/

(I obviously have to put some code in here too:)

var ctx = document.getElementById('myChart').getContext('2d');
var data = [{"x":"2021-06-01","t":null,"o":null}/* more in JsFiddle */];
var chart = new Chart(ctx, {
  type: 'bar',
  data: {
    datasets: [
      {
        backgroundColor: 'rgba(50,38,113,0.4)',
        barPercentage: 1.0,
        categoryPercentage: 1.0,
        data: data,
        label: 'Total',
        parsing: {
          yAxisKey: 't',
        },
      },
      {
        backgroundColor: 'rgba(59,191,69,0.4)',
        barPercentage: 1.0,
        categoryPercentage: 1.0,
        data: data,
        label: 'Occupied',
        parsing: {
          yAxisKey: 'o',
        },
      },
    ]
  },
  options: {
    maintainAspectRatio: false,
    responsive: true,
    scales: {
      x: {
        bounds: 'data',
        stacked: true,
        ticks: {
          autoSkip: false,
        },
        time: {
          displayFormats: {
            month: 'MMM YY',
          },
          unit: 'month'
        },
        type: 'timeseries'
      },
      y: {
        beginAtZero: true,
      },
    },
  }
});

As you can see, the data holds every day from 2021-06-01 to 2021-10-30.
Currently, the x-axis grid lines are displayed in the center of a month and the x-axis labels at the start of a month. I'd like the exact opposite:
The grid line should be before every first of a month and the labels between those lines. I just cannot find a way to manage that.

like image 662
quick-brown-fox Avatar asked Jan 27 '26 19:01

quick-brown-fox


1 Answers

Are you looking for offset: false?

options: {
  scales: {
    x: {        
      grid: {
        offset: false
      }
    }
  }
}

false should be the default value according to the docs, but maybe type: 'timeseries' changes this.

Example:

Example

like image 135
HeadhunterKev Avatar answered Jan 29 '26 10:01

HeadhunterKev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!