[Chartjs]-Can Chart.js Horizontal bar work with time series data?

1👍

The problem is that Date represents milliseconds since 1 January 1970 UTC. Therefore you need to define the start date to see only the period of interest. This can be done by adding the min option to the x-axis as follows:

min: moment().startOf('day').subtract(1, 'day') 

You should also use moment().startOf('day') when defining your data. That way, the ticks on the x-axis will be correctly positioned.

Please take a look at your amended code below and see how it works.

const data = {
  datasets: [{
      label: "Testing",
      data: [{
        x: moment().startOf('day'),
        y: 0
      }],
      backgroundColor: "red"
    },
    {
      label: "Testing",
      data: [{
        x: moment().startOf('day').add(1, 'day'),
        y: 0
      }],
      backgroundColor: "blue"
    }
  ]
};
const config = {
  type: 'bar',
  data,
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          title: () => ''
        }
      }
    },
    indexAxis: 'y',
    scales: {
      x: {      
        stacked: true,
        type: 'time',
        time: {
          unit: 'day'
        },
        min: moment().startOf('day').subtract(1, 'day')
      },
      y: {
        stacked: true
      }
    }
  }
};

new Chart("myChart", config)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>

<canvas id="myChart" height="90"></canvas>

Leave a comment