Sangeetha
Sangeetha

Reputation: 167

ChartJs - Doughnut Chart - how to remove labels if percentage is less than a limit

I am using doughnut from chart.js for visualization in my application. I need to remove the label if the percentage is bellow a static value like ,20% This is what i used to generate the labels

 var myChartOptions= {
    responsive: true,
    animation: {
      animateScale: true,
      animateRotate: true
    },
    plugins: {
         labels: {
      render: 'percentage',
      fontColor: '#000000',
      precision: 2,
    }
    }

  };

I've been working at this for awhile now with no luck.

Upvotes: 0

Views: 1286

Answers (1)

timclutton
timclutton

Reputation: 13004

It looks like chartjs-plugin-labels is being used, in which case passing a custom function to the render option will do the trick, as per the documentation:

const data = [1, 2, 7],
  myChartOptions = {
    responsive: true,
    animation: {
      animateScale: true,
      animateRotate: true
    },
    plugins: {
      labels: {
        render: args => {
          if (args.percentage < 20) {
            return '';
          }
          return args.percentage + '%';
        },
        fontColor: '#000000',
        precision: 2,
      }
    }
  };

new Chart(document.getElementById('myChart'), {
  type: 'doughnut',
  data: {
    datasets: [{
      label: 'series 1',
      data: data,
      backgroundColor: ['pink', 'lightgreen', 'lightblue'],
    }]
  },
  options: myChartOptions
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<canvas id="myChart"></canvas>

Upvotes: 1

Related Questions