Chart.js Usage
To create charts using Chart.js, you need to initialize the Chart class and pass in the chart node:
HTML Canvas code, where the chart will be displayed:
<canvas id="myChart" width="400" height="400"></canvas>
Get the node in different ways:
Initialization Methods
// Any of the following methods can be used
const ctx = document.getElementById('myChart'); // Get the node
const ctx = document.getElementById('myChart').getContext('2d'); // getContext() method returns the canvas context
const ctx = $('#myChart'); // jQuery get
const ctx = 'myChart'; // Pass in the node ID
After obtaining the element node with the above code, we can create our own chart type.
The following example creates a simple line chart:
Example
const ctx = document.getElementById('myChart');
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; // Set labels on the X-axis
const data = {
labels: labels,
datasets: [{
label: 'My First Line Chart',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)', // Set the line color
tension: 0.1
}]
};
const config = {
type: 'line', // Set the chart type
data: data,
};
const myChart = new Chart(ctx, config);
The output result of the above example is:
The following example creates a bar chart showing votes with different colors.
Example
const ctx = document.getElementById('myChart');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
The output result of the above example is:
Configuration Object Structure
The common structure of the configuration object is as follows:
const config = {
type: 'line',
data: {},
options: {},
plugins: []
}
Parameter Explanation:
type
-- Specifies the type of chartdata
-- The dataset displayed in the chartoptions
-- Optional configurations, which vary for different types of chartsplugins
-- Plugins