Chartjs-Simple example for plotting purchase data (time vs value) via Chart.js

1👍

To display time on the X axis, you’ll need both a date library and the corresponding adapter

Here’s an example using both luxon.js and chartjs-adapter-luxon

const ctx = document.getElementById('myCanvas');

const cfg = {
  type: "line",
  data: {
    datasets: [{
        data: [{
            x: "2013-03-15T09:30:00Z",
            y: 120
          },          
          {
            x: "2014-05-20T14:45:00Z",
            y: 85
          },
          {
            x: "2015-08-10T11:00:00Z",
            y: 200
          },
          {
            x: "2015-09-10T11:00:00Z",
            y: 65
          },         
          {
            x: "2015-10-10T11:00:00Z",
            y: 175
          },
          {
            x: "2015-11-10T11:00:00Z",
            y: 120
          },        
          {
            x: "2015-12-10T11:00:00Z",
            y: 135
          },
          {
            x: "2015-12-25T11:00:00Z",
            y: 55
          },       
          {
            x: "2015-12-31T11:00:00Z",
            y: 150
          },       
          {
            x: "2016-01-05T16:20:00Z",
            y: 75
          },
        ],
      label:'A',
      },
    ]
  },
  options: {
    scales: {    
      x: {
        type: "time",
      }
    }
  }
};

const myLine = new Chart(ctx, cfg);
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>
<canvas id="myCanvas"></canvas>

PS : You can also use Epoch and Unix timestamps in milliseconds as x value

Leave a comment