Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datalabels not showing on Chart.js

I am trying to display the total amount at the top of my chart.js; I'm trying to use the datalabel plugin but I'm not sure why it is not showing the labels, I don't get any errors, here's my code:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
var ctx = document.getElementById('myChart');
Chart.register(ChartDataLabels);
Chart.defaults.set('plugins.datalabels', {
  color: '#FE777B'
});
var myChart = new Chart(ctx, {
    type: 'bar',
    plugins: [ChartDataLabels],
    data: {
        datasets: [{
            data: <?php print_r($barData); ?>,
            label: 'Advisor Closed MTD',
            backgroundColor: 'rgb(192,111,94)',
            barThickness: 25,
            datalabels: {
                color: '#FFCE56'
            }
            
        }],
    },
    options: {
        responsive: false,
        plugins: {
            datalabels: {
                color: 'blue'
            }
        }
    }
});
</script>

The chart shows the right information but the labels are not showing at all.

like image 483
Riquelmy Melara Avatar asked Sep 05 '25 01:09

Riquelmy Melara


1 Answers

The labels are showing, they are in the bars itself, to show them on top of the bars you will need to configure it like so:

options: {
      responsive: false,
      plugins: {
        datalabels: {
          anchor: 'end',
          align: 'end',
          labels: {
            value: {
              color: 'blue'
            }
          }

        }
      }
    }

Example:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="myChart" width="850" height="520"></canvas>
<script>
  var ctx = document.getElementById('myChart');
  Chart.register(ChartDataLabels);
  Chart.defaults.set('plugins.datalabels', {
    color: '#FE777B'
  });
  var myChart = new Chart(ctx, {
    type: 'bar',
    plugins: [ChartDataLabels],
    data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
        data: [12, 19, 3, 5, 2, 3],
        label: 'Advisor Closed MTD',
        backgroundColor: 'rgb(192,111,94)',
        barThickness: 25,
        datalabels: {
          color: '#FFCE56'
        }

      }],
    },
    options: {
      responsive: false,
      plugins: {
        datalabels: {
          anchor: 'end',
          align: 'end',
          labels: {
            value: {
              color: 'blue'
            }
          }

        }
      }
    }
  });

</script>
like image 143
LeeLenalee Avatar answered Sep 09 '25 08:09

LeeLenalee