[Chartjs]-Show datalabels only if label value > 0

1👍

You can use the formatter function for this, if the value is bigger then 0 return it, else return an empty string:

Chart.register(ChartDataLabels)

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 0, 5, 2, 3],
      backgroundColor: 'pink'
    }]
  },
  options: {
    plugins: {
      datalabels: {
        color: 'red',
        formatter: (val) => (val > 0 ? val : '')
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

0👍

I found a solution:

 datalabels: {
        anchor: 'center',
        align: 'center',
        display: function(context) {
          return context.dataset.data[context.dataIndex]! >= 6; // or >= 1 or ...
        }
      }

Leave a comment