How to usethe yAxisID Option in Chart.js
In this approach, we are using the yAxisID option to link each dataset with a specific Y-axis in Chart.js. By defining the separate scales as “first” and “second“, both have separate styling and position. By using this, we can show the data in two Y-axes in left and right positions.
Syntax:
datasets: [
{
yAxisID: 'yourAxisID',
label: 'Dataset Label',
data: data
},
],
Example: Below is the implementation of the above-discussed approach.
HTML
<!DOCTYPE html> < html > < head > < title >Example 1</ title > < script src = "https://cdn.jsdelivr.net/npm/chart.js" > </ script > </ head > < body > < h1 style = "color: green;" > w3wiki </ h1 > < h3 > Approach 1: Using yAxisID Option </ h3 > < canvas id = "chart1" ></ canvas > < script > const ctx = document. getElementById('chart1'). getContext('2d'); const chart1 = new Chart(ctx, { type: 'line', data: { labels: ['Jan', 'Feb', 'March', 'April'], datasets: [ { yAxisID: 'first', label: 'Programming Category Views', data: [4321, 6531, 1111, 4444], borderWidth: 1, backgroundColor: 'blue', borderColor: 'blue' }, { yAxisID: 'second', label: 'Courses Growth', data: [11, 13, 15, 17], backgroundColor: 'green', borderColor: 'green' } ] }, options: { responsive: true, scales: { first: { type: 'linear', position: 'left', ticks: { beginAtZero: true, color: 'red' }, grid: { display: false } }, second: { type: 'linear', position: 'right', ticks: { beginAtZero: true, color: 'green' }, grid: { display: false } }, x: { ticks: { beginAtZero: true } } } } }); </ 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