In this article, we will learn how to show values on top of bars for a chart using the ChartJS CDN library.
Approach
- Use the <canvas> tag to show the bar graph in the HTML template.
- In the script section of the code, instantiate the ChartJS object by setting the type, data, and options properties of the library.
- Set other required options inside each property like datasets, label, borderColor, fill, scales, and others.
- Before proceeding further, we will have to install a plugin chartjs-datalabels-plugin, which will help us display labels on data for any type of chart.
- The formatter function is used to determine the content of the label, and in this case, it simply returns the data value.
CDN Links:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
Syntax:
const chart = document.getElementById('myChart');
new Chart(chart, {
type: 'bar',
data: { ... },
options: {
plugins: {
datalabels: {
anchor: 'end', // Position of the labels (start, end, center, etc.)
align: 'end', // Alignment of the labels (start, end, center, etc.)
color: 'blue', // Color of the labels
font: {
weight: 'bold',
},
formatter: function (value, context) {
return value; // Display the actual data value
}
}
}
}
});
Example: The following code shows a simple example of a bar chart showcasing the release year of web frameworks with a list of web frameworks on the x-axis and a number dataset on the y-axis.
HTML
<!DOCTYPE html> < html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport"
content = "width=device-width, initial-scale=1.0" >
< style >
body {
background-color: rgb(239, 237, 237);
}
</ style >
< title >Chart</ title >
</ head >
< body >
< div >
< canvas id = "myChart" ></ canvas >
</ div >
< script src =
</ script >
< script src =
</ script >
< script >
const ctx = document.getElementById('myChart');
// Manually register the chartjs datalabels plugin
Chart.register(ChartDataLabels);
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Node.js', 'Angular', 'React',
'Express', 'ASP.NET', 'jQuery'],
datasets: [{
label: `Release Year (in 2000's)`,
data: [9, 10, 13, 10, 2, 6],
borderWidth: 3,
backgroundColor: 'lightblue',
borderColor: 'blue'
}]
},
options: {
plugins: {
title: {
display: true,
text: 'Release Year of Web Frameworks',
color: 'blue',
font: {
weight: 'bold',
size: 20
}
},
datalabels: {
// Position of the labels
// (start, end, center, etc.)
anchor: 'end',
// Alignment of the labels
// (start, end, center, etc.)
align: 'end',
// Color of the labels
color: 'blue',
font: {
weight: 'bold',
},
formatter: function (value, context) {
// Display the actual data value
return value;
}
}
}
}
});
</ script >
</ body >
</ html >
|
Output:
Recommended Articles