[Chartjs]-Chart.js – changing tick / label positions for x axis time series

2πŸ‘

I think the problem is at these lines

    var nextPx = this.right;
    var nextTick = ticks[index + 1];
    if (nextTick) {
       nextPx = this.getPixelForOffset(nextTick.value);
       return px - (nextPx - px) / 2;
    }
    else{
       var prevTick = ticks[index - 1];
       prevPx = this.getPixelForOffset(prevTick .value);
       return px - (px - prevPx ) / 2;
//       return px + (px - prevPx ) / 2;   if the above statement don't work

    }

When nextTick is null, nextPx takes the value of this.right which creates problem. You have to add an else block for nextTick to handle the rightmost label.
I updated the code for else block. Its just an idea, you may find a better way.

0πŸ‘

You could simply define offset: true on your x-axes as follows:

options: {
  scales: {
    xAxes: [{
      offset: true,
      ...

Please have a look at below runnable code snippet.

new Chart("chart", {
  type: 'bar',
  data: {
    labels: ["2020-05-13", "2020-05-11", "2020-05-12", "2020-05-14", "2020-05-09", "2020-05-10"],
    datasets: [{
      label: "My Dataset",
      backgroundColor: "#02a499",
      borderColor: "#ffffff",
      borderWidth: 1,
      hoverBackgroundColor: "#02a499",
      hoverBorderColor: "#02a499",
      data: [20, 11, 9, 22, 11, 9]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        offset: true,
        type: 'time',
        time: {
          unit: 'day',
          source: 'data',
          tooltipFormat: 'MMM DD'
        },
        gridLines: {
          display: false
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        },
        gridLines: {
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="chart" height="120"></canvas>

0πŸ‘

Based on @MuhammadUmarFarooq answer I implemented the following code to check for the previous tick if there isn’t a next one. I am using distribution: 'series' so all the ticks on the x axis should be the same distance so I just to calculate the distance between any two.

// Get the next tick's pixel value.
        var nextPx = this.right;
        var nextTick = ticks[index + 1];
        if (nextTick) {
            nextPx = this.getPixelForOffset(nextTick.value);
        } else {
            var previousPx = this.left;
            var previousTick = ticks[index - 1];
            previousPx = this.getPixelForOffset(previousTick.value);
            return previousPx + (px - previousPx) / 2;
        }

Leave a comment