[Chartjs]-Render pie chart datasets out of 100% — Chart.JS

1👍

Check this code (comments added):

window.onload = () => {
  const chart = document.getElementById('chart').getContext('2d');
  const data = [5, 0];
  
  // Count the sum and minus from 100 => (100 - 5 + 0) = 95,
  // so it will be the remaining part
  let remainingPart = 100 - data.reduce((prev, curr) => prev + curr, 0);
  // Further you can check if the value get's negative
  remainingPart = remainingPart < 0 ? 0 : remainingPart;
  new Chart(chart, {
      type: 'pie',
      data: {
          datasets: [
              {
                  borderColor: '#08c',
                  borderWidth: 1,
                  // Here the color is transparent for it.
                  backgroundColor: ['#38c172', '#08c', 'transparent'],
                  data: [...data, remainingPart]
              }
          ]
      },
      options: {
          tooltips: {
              enabled: false
          },
          events: []
      }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

<canvas id="chart" />

Leave a comment