Chartjs-Chart.js time series multi axis case

0👍

You can just add an extra scale in the scale config and use the yAxisID in the dataset to link to it

var options = {
  type: 'line',
  data: {
    datasets: [{
        label: '# of Votes',
        data: [{
          x: new Date('09-08-2021 12:04'),
          y: 10
        }, {
          x: new Date('09-08-2021 12:08'),
          y: 15
        }, {
          x: new Date('09-08-2021 12:12'),
          y: 5
        }, {
          x: new Date('09-08-2021 12:30'),
          y: 8
        }],
        borderColor: 'pink',
        yAxisID: 'y'
      },
      {
        type: 'bar',
        label: '# of Points',
        data: [{
          x: new Date('09-08-2021 12:04'),
          y: 4
        }, {
          x: new Date('09-08-2021 12:08'),
          y: 6
        }, {
          x: new Date('09-08-2021 12:12'),
          y: 12
        }, {
          x: new Date('09-08-2021 12:30'),
          y: 18
        }, {
          x: new Date('09-08-2021 12:022'),
          y: 10
        }, {
          x: new Date('09-08-2021 12:38'),
          y: 15
        }, {
          x: new Date('09-08-2021 12:52'),
          y: 5
        }, {
          x: new Date('09-08-2021 12:59'),
          y: 8
        }],
        backgroundColor: 'orange',
        yAxisID: 'y2'
      }
    ]
  },
  options: {
    scales: {
      x: {
        type: 'time',
      },
      y: {
        title: {
          display: true,
          text: 'Car Speed, mph',
          font: {
            size: 24
          }
        }
      },
      y2: {
        position: 'right',
        title: {
          display: true,
          text: 'secondY',
          font: {
            size: 24
          }
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

Leave a comment