Skip to content Skip to sidebar Skip to footer

How To Use Chart.js Plugin Data-labels With Ng2-chart?

Well, here I am again with my Angular and javascript woes feeling dumber for each question I ask. But let me try to explain my initial steps and how it lead to this problem. So, i

Solution 1:

Well, since there was literally no answer, I could ultimately settle for the "Global" Chart solution.

Chart.pluginService.register({
  // I gave it an id, so I could disable the plugin if neededid: 'p1', 
  afterDatasetsDraw: function (chart, _ease) {

    let width = chart.chart.width;
    let ctx = chart.chart.ctx;

    let datasets = chart.data.datasets;

    datasets.forEach(function (_dataset, index) {
      let meta = chart.getDatasetMeta(index);

      // grabbing the array with the data...let barLabelData = meta.controller._data;
      // console.log(meta.controller._data)if (!meta.hidden) {
        meta.data.forEach(function (segment, _index) {
          let model = segment._model;
          let position = segment.tooltipPosition();


          let x = position.x;
          let y = position.y;

          let height = model.height;

          ctx.restore();

          ctx.textBaseline = "middle";
          // var fontSize = (height / 114).toFixed(2);
          ctx.font = 'bold ' + height / 2 + 'px Arial';
          ctx.fillStyle = '#777'; //first label's font colorlet text = barLabelData[_index];

          ctx.fillText(text, x, y);
          ctx.save();


        })

      }

    });

  }
});

Which ultimately graced me with a sorta okay looking chart. So yeah, it's not at clean as I would like to. But there are still issues with implementation.

My Chart component globally implements my plugin logic. That's awful deisgn here and I have to decouple it. The minor problem is, I have to make sure the labels work always and are properly depicted. But for now I'm pleased it works.

enter image description here

Solution 2:

Here's an example done by @paviad:

https://stackblitz.com/edit/ng2-charts-bar-labels

import { Component, OnInit } from'@angular/core';
import { ChartOptions, ChartType, ChartDataSets } from'chart.js';
import * as pluginDataLabels from'chartjs-plugin-datalabels';
import { Label } from'ng2-charts';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
exportclassAppComponent {
  publicbarChartOptions: ChartOptions = {
    responsive: true,
    // We use these empty structures as placeholders for dynamic theming.scales: { xAxes: [{}], yAxes: [{}] },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
        font: {
          size: 20,
        }
      }
    }
  };

...
public barChartPlugins = [pluginDataLabels];
...

Detailed options are here: https://chartjs-plugin-datalabels.netlify.app/

Post a Comment for "How To Use Chart.js Plugin Data-labels With Ng2-chart?"