Chartjs-Data Labels on top of points in line charts

0👍

You can build a plugin to get this working. I have this working in a vue build at the moment but I’ve tried to adapt it for you as much as I can.

Template

template: `
  <base-chart
    class="chart"
    [datasets]="datasets"
    [labels]="labels"
    [options]="options"
    [chartType]="'line'"
    [plugin]="dataLabelPlugin">
  </base-chart>
`

Js add in plugin

private options = {
  scales: {
    yAxes: [{
      ticks: {
        beginAtZero: true
      }
    }]
  }
  plugins: [{
    afterDatasetsDraw: this.dataLabelPlugin
  }]
};

Js define a plugin that draws in the numbers after each animation. You might need to pass in the chart you are modifying depending on the context.

private dataLabelPlugin = function(chart, easing) {
    // To only draw at the end of animation, check for easing === 1
    const ctx = chart.ctx;
    const fontSize = 12;
    const fontStyle = 'normal';
    const fontFamily = 'open sans';
    const padding = 5;

    chart.data.datasets.forEach((dataset, key) => {
        let meta = chart.getDatasetMeta(key);
        if (!meta.hidden) {
            meta.data.forEach((element, index) => {
                let position = element.tooltipPosition();
                // Just naively convert to string for now
                let dataString = dataset.data[index].toString();

                ctx.fillStyle = '#676a6c';

                ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
                // Make sure alignment settings are correct
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
            });
        }
    });
};

If you get this working let me know and I can make changes to make this answer more correct.

Leave a comment