Chartjs-Bar Chart in Angular JS Using Chartjs

1👍

For this type of feature you should use the chartjs-plugin-datalabels which does exactly this.

Something like this should solve your problem:

options: {
  plugins: {
    datalabels: {
      color: 'blue',
      labels: {          
        value: {
          color: 'green'
        }
      }
    }
  }
}

The documentation is quite good. You should find everything you need there.

1👍

If you dont want to use the datalabels plugin you can write your own basic version of it as an inline plugin like so:

const customDatalabalesPlugin = {
  id: 'customDatalabels',
  afterDatasetsDraw: (chart, args, opts) => {
    const {
      ctx,
      _metasets
    } = chart;
    const lineHeight = ctx.measureText('M').width;
    const color = opts.color || 'black';

    for (let i = 0; i < chart.data.datasets.length; i++) {
      const meta = chart.getDatasetMeta(i)
      meta.data.forEach((el) => {
        //console.log(el)
        const dpVal = el._chart.data.datasets[el._datasetIndex].data[el._index];
        const text = dpVal.toString();
        const textWidth = ctx.measureText(text).width;

        ctx.fillStyle = color;
        ctx.fillText(text, (el._model.x - textWidth / 2), (el._model.y - lineHeight));
      });
    }
  }
}

const options = {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12.4, 19.234, 3.23213, 5.4, 2, 3],
      borderColor: 'pink'
    }]
  },
  options: {
    plugins: {
      customDatalabels: {
        color: 'green', // Color each character individual collor
        // color: 'pink' // Color whole label this collor
      }
    }
  },
  plugins: [customDatalabalesPlugin]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

About using private variables in the plugin, it can be done savely since there wont be another release of version 2 for chart.js so they wont get changed anymore.

Leave a comment