Categories
JavaScript Answers

How to use two Y axes in Chart.js v2 and JavaScript?

Spread the love

Sometimes, we want to use two Y axes in Chart.js v2 and JavaScript.

In this article, we’ll look at how to use two Y axes in Chart.js v2 and JavaScript.

How to use two Y axes in Chart.js v2 and JavaScript?

To use two Y axes in Chart.js v2 and JavaScript, we can put the axes in the yAxes array property.

For instance, we write

const canvas = document.getElementById("chart");
new Chart(canvas, {
  type: "line",
  data: {
    labels: ["1", "2", "3", "4", "5"],
    datasets: [
      {
        label: "A",
        yAxisID: "A",
        data: [100, 50, 0],
      },
      {
        label: "B",
        yAxisID: "B",
        data: [1, 1, 1],
      },
    ],
  },
  options: {
    scales: {
      yAxes: [
        {
          id: "A",
          type: "linear",
          position: "left",
        },
        {
          id: "B",
          type: "linear",
          position: "right",
          ticks: {
            max: 1,
            min: 0,
          },
        },
      ],
    },
  },
});

to set yAxes to an array with the properties for each y-axis.

We set the type, position, and the min and max ticks values.

Conclusion

To use two Y axes in Chart.js v2 and JavaScript, we can put the axes in the yAxes array property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *