ArticleZip > How To Use Two Y Axes In Chart Js V2

How To Use Two Y Axes In Chart Js V2

Chart.js V2 is a popular library for creating dynamic and visually appealing charts on the web. One feature that users often find helpful is the ability to use two Y axes in a single chart. This allows for better representation of data when you have multiple data sets with different ranges or units.

To use two Y axes in Chart.js V2, you need to define your chart configuration with the appropriate settings. Let's walk through the steps to achieve this.

Start by creating a new Chart object and defining your data sets. In your dataset definition, specify the Y axis you want each dataset to be associated with using the `yAxisID` property. For example, to create two datasets associated with different Y axes, your data configuration might look like this:

Javascript

const data = {
  datasets: [
    {
      label: 'Dataset 1',
      data: [10, 20, 30, 40, 50],
      yAxisID: 'y-axis-1',
    },
    {
      label: 'Dataset 2',
      data: [1, 2, 3, 4, 5],
      yAxisID: 'y-axis-2',
    },
  ]
};

Next, you need to define your Y axes. In the options section of your chart configuration, specify your Y axes settings. You can define multiple Y axes by providing an array of axis configurations in the `yAxes` property. Each Y axis configuration should have a unique `id` that matches the `yAxisID` specified in your dataset definition.

Javascript

const options = {
  scales: {
    yAxes: [
      {
        type: 'linear',
        display: true,
        position: 'left',
        id: 'y-axis-1',
      },
      {
        type: 'linear',
        display: true,
        position: 'right',
        id: 'y-axis-2',
      },
    ]
  }
};

In this example, we've defined two Y axes, one on the left and one on the right. The `id` of each axis matches the `yAxisID` of the datasets, so each dataset will be associated with the correct Y axis.

Finally, when you create your Chart object, specify your data and options objects to render the chart with two Y axes:

Javascript

const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options
});

By following these steps, you can create a chart with two Y axes in Chart.js V2. This feature is particularly useful when you need to compare datasets with different units or scales. Experiment with different chart types and options to customize the appearance and functionality of your dual-axis chart.

×