0
votes

I would like to ask how to choose which data labels should be visible on the line chart? It looks like on the screenenter image description here

But it's not nice. I would like to have visible only every second the label. I thought to check how many labels there are. Then if more than X choose only some, but maybe there is something easier.

Here is the code from labels:

options: {
        plugins: {
            datalabels: {
                align: 'top',
                color: '#000000',
                font: {
                    weight: 'bold',
                    size: '16'
                }
            }
        },
        title: {
          display: true,
          text: 'Level'
        }
      }

Any ideas?

1

1 Answers

1
votes

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 : ''
    }
    ...