Chartjs-Time format on the x axis in Chart.js

1๐Ÿ‘

โœ…

I found out, where the problem was:

I needed to reference an adaptor for the moment like this and remove the the square brackets for the properties of the axis as shown in the documetnation:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@0.1.2"></script>

<canvas id="mychart"></canvas>
    <script>
    
    data = [{
          x: new Date("2017-01-20"),
          y: 43
        }, {
          x: new Date("2017-01-21"),
          y: 45
        }, {
          x: new Date("2017-01-22"),
          y: 120
        }, {
          x: new Date("2017-01-23"),
          y: 100
        }]
    let options = {
      scales: {
        yAxes: {ticks: {min: 0}},
        xAxes: {
            type: 'time',
            time: {
              unit: 'day',
              tooltipFormat: 'MMM DD'
            }
          },
      },
    };
    
    let chartData = {
        //labels: labels,
      datasets: [{
        data: data,
        label: 'Amount of Stuff',
        backgroundColor: '#fffff',
      }]
    };
    
    let ctx = document.getElementById('mychart').getContext('2d');
    
    new Chart(ctx, {
        data: chartData,
      type: 'scatter',
      options: options,
    });
    </script>

1๐Ÿ‘

You can use a callback function to alter how the data on the axis is displayed.

let options = {
  scales: {
    yAxes: [{ticks: {min: 0}}],
    xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        },
        ticks: {
            callback: function(value, index, values){
                // do something with value
                return value;
            }
        }
      }],
  },
};

Leave a comment