Search code examples
vue.jschartsvue-chartjs

set the position of data label according to vertical bar chart column height


I am using vue chat js with chart js 2.9.4 package. And chart js plugin datalabels also plugged in to show data labels. I created a vertical bar chart and when some columns height is lower, data label is overlapped with x-axis. In order to avoid that I did as follows.

 plugins: {
   datalabels: {
     align(context) {
          const index = context.dataIndex
          const value = context.dataset.data[index]
          return value < 10 ? 'top' : 'center'
     },
   }
 }

There as you can see I had to add a condition manually to set the position of the data label. If the value is less than 10, then data label should be on top and if it's more than or equal to 10 it should be on center. But you know that value 10 in the condition should be dynamic. So is there any way to identify this overlap behavior in the used plugin or any good equation to fix this issue?


Solution

  • Take the max value of the dataset you are showing

      const data = context.dataset.data
      const max = Math.max( ...data )
    

    Then, if for the given bar it is lower than the 10% (or some other percentil) of the max bar value then just do what you where doing.

    All together:

      const index = context.dataIndex
      const data = context.dataset.data
      const max = Math.max( ...data )
      const percentil = 0.10
      const value = data[index]
      return value < max * percentil ? 'top' : 'center'