Chart.js - Writing Labels Inside of Horizontal Bars?

With reference to the original solution to displaying data value by using HTML5 Canvas fillText() method in the animation's onComplete, the code below will get you what you need:

The key to custom-displaying any chart related data is inspecting the chart's dataset as in this.data.datasets below. I did this by inspecting where the different values are in this dataset, as well as the position to place them for the fillText method.

Inspecting the chart's dataset: Image

Script (Chart.js 2.0 & up):

var barOptions = {
      events: false,
        showTooltips: false,
      legend: {
        display: false
      },
      scales:{
        yAxes: [{
          display: false
        }]
      },
        animation: {
        onComplete: function () {
          var ctx = this.chart.ctx;
          ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
          ctx.textAlign = 'left';
          ctx.textBaseline = 'bottom';

          this.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
              var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
                  left = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._xScale.left;
              ctx.fillStyle = '#444'; // label color
              var label = model.label;
              ctx.fillText(label, left + 15, model.y + 8);
            }
          });               
        }
        }
    };

jsFiddle: http://jsfiddle.net/jfvy12h9/


You can achieve this effect in chartjs 2.0 + by rotating the labels 90 degrees and applying negative padding, so that the label moves up inside the 'bar'. Something like this:

new Chart(document.getElementById(id), {
  type: 'bar',
  data: data,
  options: {
    scales: {
      xAxes: [
        {
          ticks: {
            autoSkip: false,
            maxRotation: 90,
            minRotation: 90,
            padding: -110
          }
        }
      ]
    }
  }
});

See the tick configuration documentation for more information.


There is now on option "mirror" to make the label appear inside the bar.

Example of "options" config for a horizontalBar chart :

options: {
    scales: {
        yAxes: [{ticks: {mirror: true}}]
    }
}

Doc : http://www.chartjs.org/docs/latest/axes/cartesian/#common-configuration