How to useDatasets Array for Each Axis in Chart.js
In this approach, we are creating the Bar chart with two datasets, where each dataset is lined with a separate y-axis as y-axis-1 and y-axis-2. The scales property in the options mainly configures two linear y-axis positions.
Syntax:
options: {
scales: {
yAxes: [
{
// left y-axis
},
},
{
// right y-axis
},
},
],
},
}
Example: Below is the implementation of the above-discussed approach.
HTML
<!DOCTYPE html> < html > < head > < title >Example 2</ title > < script src = "https://cdn.jsdelivr.net/npm/chart.js" > </ script > </ head > < body > < center > < h1 style = "color: green;" > w3wiki </ h1 > < h3 > Approach 2: Using datasets Array for Each Axis </ h3 > < canvas id = "chart2" width = "400" height = "200" > </ canvas > </ center > < script > const data = { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'], datasets: [ { label: 'Page Views', data: [500, 600, 800, 700, 900], yAxisID: 'y-axis-1', backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }, { label: 'Users', data: [30, 70, 50, 80, 60], yAxisID: 'y-axis-2', backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1 } ] }; const config = { type: 'bar', data: data, options: { scales: { yAxes: [ { type: 'linear', position: 'left', id: 'y-axis-1', }, { type: 'linear', position: 'right', id: 'y-axis-2', }, ] } } }; const chart2 = new Chart( document.getElementById('chart2'), config); </ script > </ body > </ html > |
Output:
How to use Two Y Axes in Chart.js ?
In Chart.Js, while representing the complex and multi-datasets in visual form, we always need to use two or more Y-axes to show the data. So we can use two Y-axes in ChartJS by using various approaches. In this article, we will see these approaches to make the Chart with dual Y-axis.
Table of Content
- Using the yAxisID Option
- Using Datasets Array for Each Axis