[Chartjs]-Label is not showing in ChartJS

1👍

I solved this problem by adding an empty title to the chart, so it will create space above the chart and show labels above the bar

options: {
    title: {
        display: true,
        text: ' '
    },
....

0👍

This looks like a clear case of the datalabels going out of the canvas since the bar takes height dynamically as per the data values. You can set the max y-tick setting to solve this. Here is the jsfiddle -> https://jsfiddle.net/Luaf2tm4/5979/

Hope it helps!

var canvas = document.getElementById('myChart');
var data = {
  labels: ["January", "February", "March", "April", "May", "June"],
  datasets: [{
    label: "My First dataset",
    backgroundColor: "rgba(255,99,132,0.2)",
    borderColor: "rgba(255,99,132,1)",
    borderWidth: 2,
    hoverBackgroundColor: "rgba(255,99,132,0.4)",
    hoverBorderColor: "rgba(255,99,132,1)",
    data: [500, 2000, 800, 600, 950, 890],
  }]
};

function getOptions(displayLegend = false) {
  return {
    events: false,
    showTooltips: false,
    legend: {
      display: displayLegend
    },
    scales: {
      yAxes: [{
        display: true,
        stacked: true,
        ticks: {
            stepSize: 200,
          min: 0, // minimum value
          max: 2200 // maximum value, you can either hard code if you know your datainput, else computer the value through some logic i.e taking the max value from the dataset and adding some extra value to it. 
        }
      }]
    },
    animation: {
      duration: 0,
      onComplete: function() {
        var ctx = this.chart.ctx;
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseLine = 'bottom';
        ctx.fillStyle = '#0b7707';

        this.data.datasets.forEach(function(dataset) {
          console.log(dataset);
          for (var i = 0; i < dataset.data.length; i++) {
            for (var key in dataset._meta) {
              var model = dataset._meta[key].data[i]._model;
              ctx.fillText(dataset.data[i], model.x, model.y - 10);
            }
          }
        });
      }
    }
  };
}

var myBarChart = Chart.Bar(canvas, {
  data: data,
  options: getOptions()
});

Leave a comment