Issue
I have tried a lot to show values on top of char but I couldn't do it please could you help me with this i have also add plugins to show data.
<canvas id="myChart" width="200" height="100" aria-label="Hello ARIA World" role="img"></canvas>
<script>
const ctx = document.getElementById('myChart');
console.log({{sales_performance|safe}})
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Sales',
data: [1, 10, 10, 11, 1, 10, 10, 11, 1, 10, 11, 16],
borderWidth: 1
}]
},
options: {
scales: {
y: {
display: false, // Hide the y-axis label
beginAtZero: true
}
},
plugins: {
datalabels: {
color: 'black', // Set the color of the data labels
font: {
weight: 'bold'
},
formatter: function(value, context) {
return value; // Display the value on the bars
}
}
}
}
});
</script>
I want to show values on top of each bar column.
Solution
This is a common mistake that the chartjs-plugin-datalabels not working due to the library is not registered. You must register the library as stated in the documentation stated.
To position the data label on top of the bar chart, you need to add the datalabels property in each object of the dataLabels array. You may read the Positioning for the configuration.
datasets: [
{
...
datalabels: {
align: 'top',
anchor: 'end',
},
}
]
Complete code:
new Chart(ctx, {
type: 'bar',
data: {
labels: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'July',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
],
datasets: [
{
label: 'Sales',
data: [1, 10, 10, 11, 1, 10, 10, 11, 1, 10, 11, 16],
borderWidth: 1,
datalabels: {
align: 'top',
anchor: 'end',
},
},
],
},
options: {
scales: {
y: {
display: false, // Hide the y-axis label
beginAtZero: true,
},
},
plugins: {
datalabels: {
color: 'black', // Set the color of the data labels
font: {
weight: 'bold',
},
formatter: function (value, context) {
return value; // Display the value on the bars
},
},
},
},
plugins: [ChartDataLabels],
});
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.