How to add multiple Chart.js charts in the same page with JavaScript?

Sometimes, we want to add multiple Chart.js charts in the same page with JavaScript.

In addition, we’ll look at how to add multiple Chart.js charts in the same page with JavaScript.

How to add multiple Chart.js charts in the same page with JavaScript?

To add multiple Chart.js charts in the same page with JavaScript, we can add multiple canvas elements and render a chart in each.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<canvas id="myChart" width="400" height="400"></canvas>
<canvas id="myChart2" width="400" height="400"></canvas>

to add the Chart.js script tag and 2 canvas elements.

Then we render a chart in each by writing:

const ctx = document.getElementById('myChart');
const ctx2 = document.getElementById('myChart2');

const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      fill: true,
      borderWidth: 1,
    }]
  },
});

const myChart2 = new Chart(ctx2, {
  type: 'line',
  data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      fill: true,
      borderWidth: 1,
    }]
  },
});

We select the canvas elements with document.getElementById.

Then we call the Chart constructors with each canvas element and objects with some chart options.

Now we should see 2 charts displayed.

Conclusion

To add multiple Chart.js charts in the same page with JavaScript, we can add multiple canvas elements and render a chart in each.