How to use two y axes in chart.js?

by darrion.kuhn , in category: Javascript , a month ago

How to use two y axes in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , a month ago

@darrion.kuhn 

To use two y-axes in Chart.js, you can use the yAxes property within the scales option. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var ctx = document.getElementById("myChart").getContext("2d");

var myChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
      {
        label: "Dataset 1",
        data: [12, 19, 3, 5, 2, 3],
        yAxisID: 'y-axis-1',
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgba(255, 99, 132, 1)",
        borderWidth: 1
      },
      {
        label: "Dataset 2",
        data: [200, 150, 300, 250, 100, 150],
        yAxisID: 'y-axis-2',
        backgroundColor: "rgba(54, 162, 235, 0.2)",
        borderColor: "rgba(54, 162, 235, 1)",
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [
        {
          id: 'y-axis-1',
          position: 'left',
          ticks: {
            beginAtZero: true
          }
        },
        {
          id: 'y-axis-2',
          position: 'right',
          ticks: {
            beginAtZero: true
          }
        }
      ]
    }
  }
});


In the above code, we create a line chart with two datasets (Dataset 1 and Dataset 2). Each dataset is associated with a specific y-axis using the yAxisID property.


The scales option is used to specify the configuration of the axes. In the yAxes property, we define two axes - y-axis-1 and y-axis-2 - and set their position (left and right, respectively) and ticks configuration.


This configuration allows you to display two different scales on the y-axes for your datasets.