javascriptchart.jssalesforce-lightninglwc

LWC: How to display data values in chart js bars in Lightning Web Components(LwC) salesforce


I have built simple bar chart in salesforce using LwC with ChartJS version v2.8.0, so now I am trying to display the data values on each bars using chartjs-plugin-datalabels v1.0.0 plugins. I have loaded this plugin as below in the code and registered the plugin as specified in the plugin documentation but the data values are not showing up on each bars.

Can anyone point out what am I missing here? That would be helpful.

Here is the LwC code:

import { LightningElement,api, wire, track } from 'lwc';
import chartjs from '@salesforce/resourceUrl/chartjs_v280';
import ChartDataLabels from '@salesforce/resourceUrl/ChartjsPluginDataLabels';
import { loadScript } from 'lightning/platformResourceLoader';

export default class ChartDemocmp extends LightningElement {
    //chart;
    isChartJsInitialized;
    chartConfiguration;

   

    renderedCallback() {
        Promise.all([
            loadScript(this, chartjs),
            loadScript(this, ChartDataLabels)
        ])
        .then(()=>{
            console.log('Loaded');
            //this.isChartJsInitialized = true;
            
            if(this.chart){
                this.chart.destroy();//destory the chart once data is updated to show the new chart
                }
        const ctx = this.template.querySelector("canvas.barChart").getContext('2d');
        //Chart.register(ChartDataLabels);
        //chartjs.plugins.register(ChartDataLabels);
        Chart.plugins.register(ChartDataLabels);
        this.chart = new Chart(ctx,{
            type: 'bar',
    data: {
     labels: ["data1","data2","data3","data4","data5","data6","data7"],
     datasets: [
      {
       label: 'dataset',
       barPercentage: 0.5,
       barThickness: 6,
       maxBarThickness: 8,
       minBarLength: 2,
       backgroundColor: "blue",
       data: [65, 59, 80, 81, 56, 55, 40],
      },
     ],
    },
    // plugins: [ChartDataLabels],
    options: {
        resposive:true,
        plugins: {
            datalabels: {
                color: "black",
                labels: {
                    title: {
                        font: {
                            weight: "bold"
                        }
                    }
                }
            }
        }
    }
   });
    })
        .catch(error => {
           console.log('error chart--> '+JSON.stringify(error));
            
        });
    
    }

    }

Here is the screenshot of bar chart in salesforce where the values are not getting displayed on each bars:

enter image description here


Solution

  • I think the issue is depending on the missing Y scale definition where the default is ticks.beginAtZero: false. The plugin, by default, calculates the position of the labels on whole bar (based on data value) and not on visible one. To force the plugin to use the visible bar, you should use clamp: true option.

    Clamp doc: https://chartjs-plugin-datalabels.netlify.app/guide/positioning.html#clamping

    Chart.plugins.register(ChartDataLabels);
    new Chart(
     document.getElementById('myChart'),
     {
      type: 'bar',
      data: {
        labels: ["data1","data2","data3","data4","data5","data6","data7"],
        datasets: [
          {
            label: 'dataset',
            barPercentage: 0.5,
            barThickness: 6,
            maxBarThickness: 8,
            minBarLength: 2,
            backgroundColor: "blue",
            data: [65, 59, 80, 81, 56, 55, 40],
          },
        ]
      },
      options: {
        resposive:true,
        plugins: {
          datalabels: {
            clamp: true,
            color: "black",
            labels: {
              title: {
                font: {
                  weight: "bold"
                }
              }
            }
          }
        }
      }
    });
    .myChartDiv {
      max-width: 600px;
      max-height: 400px;
    }
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@1.0.0/dist/chartjs-plugin-datalabels.min.js"></script>
    <html>
      <body>
        <div class="myChartDiv">
          <canvas id="myChart" width="600" height="400"/>
        </div>
      </body>
    </html>