I am trying to use formatting in Chart.js. I’ve configured the imports correctly, but it still doesn’t display what I want
It doesn’t work on my local pc. I uploaded the same code to codepen and it didn’t work either. You can verify it here
JavaScript
x
25
25
1
var donutEl = document.getElementById("donut").getContext("2d");
2
var data = [4, 9, 5, 2];
3
4
var pieChart = new Chart(donutEl, {
5
type: 'doughnut',
6
data: {
7
datasets: [
8
{
9
data: [10, 20, 15, 5, 50],
10
backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
11
},
12
],
13
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
14
},
15
options: {
16
plugins: {
17
datalabels: {
18
formatter: (value) => {
19
return value + '%';
20
}
21
}
22
}
23
}
24
})
25
Any ideas what am I doing wrong? Thanks
Advertisement
Answer
As described here, you need to register the plugin:
JavaScript
1
2
1
Chart.register(ChartDataLabels);
2
Live example:
JavaScript
1
24
24
1
Chart.register(ChartDataLabels);
2
3
const donutEl = document.getElementById("donut").getContext("2d");
4
const data = [4, 9, 5, 2];
5
6
const pieChart = new Chart(donutEl, {
7
type: 'doughnut',
8
data: {
9
datasets: [{
10
data: [10, 20, 15, 5, 50],
11
backgroundColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
12
}, ],
13
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
14
},
15
options: {
16
plugins: {
17
datalabels: {
18
formatter: (value) => {
19
return value + '%';
20
}
21
}
22
}
23
}
24
})
JavaScript
1
5
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
3
<div class="flexWrapper">
4
<canvas id="donut" width="400" height="400"></canvas>
5
</div>