Skip to content
Advertisement

How to properly use formatting with chartjs?

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

var donutEl = document.getElementById("donut").getContext("2d");
var data = [4, 9, 5, 2];

var pieChart = new Chart(donutEl, {
type: 'doughnut',
data: {
    datasets: [
        {
            data: [10, 20, 15, 5, 50],
            backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
        },
    ],
    labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
    plugins: {
        datalabels: {
            formatter: (value) => {
                return value + '%';
            }
        }
    }
}
})

Any ideas what am I doing wrong? Thanks

Advertisement

Answer

As described here, you need to register the plugin:

Chart.register(ChartDataLabels);

Live example:

Chart.register(ChartDataLabels);

const donutEl = document.getElementById("donut").getContext("2d");
const data = [4, 9, 5, 2];

const pieChart = new Chart(donutEl, {
  type: 'doughnut',
  data: {
    datasets: [{
      data: [10, 20, 15, 5, 50],
      backgroundColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
    }, ],
    labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
  },
  options: {
    plugins: {
      datalabels: {
        formatter: (value) => {
          return value + '%';
        }
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<div class="flexWrapper">
  <canvas id="donut" width="400" height="400"></canvas>
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement