Daiane Mascarenhas
Daiane Mascarenhas

Reputation: 11

Data Labels on top of points in line charts

I'm using Angular2 with ng2-charts to create a line chart. But I'm trying to put the data labels on top of the point, just like the data label in this bar chart on the image in the link: bar chart

I found the chart.js plugin for data labels, but I can't figure it how to use it with ng2-charts.

You can see a simple example of how I'm doing my charts in the link : http: // plnkr.co/edit/GcuZd5A4J6TL29vAyTua?p=preview

Can any one help me with that?!

Upvotes: 0

Views: 2477

Answers (1)

Tom Headifen
Tom Headifen

Reputation: 1996

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.

Upvotes: 0

Related Questions