Home  >  Q&A  >  body text

How to display text on ChartJS bar chart?

I need to write text into a bar chart in a 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 above code does not work...

I need something like this:

P粉578343994P粉578343994377 days ago632

reply all(2)I'll reply

  • P粉803527801

    P粉8035278012023-10-24 13:35:12

    If you want to render centered text for each element, there is an easier way:

    Chart.helpers.each(meta.data.forEach(function (bar, index) {
        var centerPoint = bar.getCenterPoint();
        ctx.fillText(dataset.data[index], centerPoint.x, centerPoint.y));
    }),this)

    It seems that 'getCenterPoint' is not available in version 2.1.3 (which you use in your example). I tried it with 2.5.0 and it works

    reply
    0
  • P粉362071992

    P粉3620719922023-10-24 11:28:29

    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 the canvas with a container with the desired width and height

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

    And add the following to 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,

    reply
    0
  • Cancelreply