Chartjs-ChartJS โ€“ How to choose the visible datalabels

1๐Ÿ‘

โœ…

You can define a formatter that returns the value or an empty string in case you want to skip the data label.

The following formatter for example makes sure, only every second data label appears on your chart.

options: {
  plugins: {
    datalabels: {
      ...
      formatter: (value, context) => context.dataIndex % 2 == 0 ? value : ''
    }
    ...

This can be extended with a check for the total number of values. The following formatter returns every value as long as the total number of values is lower than 100. Otherwise, it only returns every second value.

options: {
  plugins: {
    datalabels: {
      ...
      formatter: (value, context) =>  context.chart.data.datasets[0].data.length < 100 || context.dataIndex % 2 == 0 ? value : ''
    }
    ...

Leave a comment