[Chartjs]-Is there a way in a donut Chart.JS to show a % out of 100

3👍

Try passing data of [3, 97]. You’re trying to use it as a loading indicator but it seems designed for showing 100% of things broken into parts.

If you pass simply [3], then that’s 100% of your dataset

2👍

Create a two value dataset, like:

[percent_value, 100-percent_value]

Here’s a full demo:

const originalDoughnutDraw = Chart.controllers.doughnut.prototype.draw;

Chart.helpers.extend(Chart.controllers.doughnut.prototype, {
  draw: function() {
    const chart = this.chart;
    const {
      width,
      height,
      ctx,
      config
    } = chart.chart;

    const {
      datasets
    } = config.data;

    const dataset = datasets[0];
    const datasetData = dataset.data;
    const completed = datasetData[0];
    const text = `${completed}% completed`;
    let x, y, mid;

    originalDoughnutDraw.apply(this, arguments);

    const fontSize = (height / 350).toFixed(2);
    ctx.font = fontSize + "em Lato, sans-serif";
    ctx.textBaseline = "top";


    x = Math.round((width - ctx.measureText(text).width) / 2);
    y = (height / 1.8) - fontSize;
    ctx.fillStyle = "#000000"
    ctx.fillText(text, x, y);
    mid = x + ctx.measureText(text).width / 2;
  }
});


var context = document.getElementById('myChart').getContext('2d');
var percent_value = 3;
var chart = new Chart(context, {
  type: 'doughnut',
  data: {
    labels: ['Completed', 'Pending'],
    datasets: [{
      label: 'First dataset',
      data: [percent_value, 100 - percent_value],
      backgroundColor: ['#00baa6', '#ededed']
    }]
  },
  options: {}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart"></canvas>

Leave a comment