javascriptchart.js

How can I show text over a ChartJS bar chart?


I need to write text into the bar in chart using chart.js

 var ctx = document.getElementById("myChart");
 var myChart = new Chart(ctx, {
     type: 'bar',
     data:data,
     options: {           
         scales: {
             yAxes: [{
                 ticks: {
                     beginAtZero:true
                 }
             }]
         }
     },
     responsive : true,
     showTooltips : false,
     showInlineValues : true,
     centeredInllineValues : true,
     tooltipCaretSize : 0,
     tooltipTemplate : "<%= value %>"
 });

the code above do not working...

i need something like this:

example


Solution

  • Add this code to your options object:

    animation: {
      onComplete: function () {
        var chartInstance = this.chart;
        var ctx = chartInstance.ctx;
        console.log(chartInstance);
        var height = chartInstance.controller.boxes[0].bottom;
        ctx.textAlign = "center";
        Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
          var meta = chartInstance.controller.getDatasetMeta(i);
          Chart.helpers.each(meta.data.forEach(function (bar, index) {
            ctx.fillText(dataset.data[index], bar._model.x, height - ((height - bar._model.y) / 2));
          }),this)
        }),this);
      }
    }
    

    https://jsfiddle.net/h4p8f5xL/

    UPDATE 2

    Surround your canvas with a container with your desired width and height

    <div style="width: 100%; height: 500px">
        <canvas id="myChart" width="400" height="400"></canvas>
    </div>
    

    and add the following into your options object

    // Boolean - whether or not the chart should be responsive and resize when the browser does.
    responsive: true,
    // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
    maintainAspectRatio: false,