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

0๐Ÿ‘

โœ…

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>

Leave a comment