[Chartjs]-How to always show a label in ChartJS in React

0👍

OK, so in the absence of figuring out how to use the vanilla method in the above, I found that the datalabels plugin is a really handy tool to achieve this.

All you have to do is run
npm install chartjs-plugin-datalabels --save

Then add to your component .js file:
import 'chartjs-plugin-datalabels';

And that’s all you need to get this:
enter image description here

There’s a great example on codesandbox that I found that demonstrates how to change the label content and formatting. It’s for a bar chart – but I didn’t find it difficult to transfer the code to my line chart.

1👍

I was having trouble to have the labels show up with 2.0.0 version of plugin and v3 of react-chartjs-2 until I found that we need to explicit registration of plugin in someway (specific charts or global) since version v1 of the plugin.

https://v2_0_0–chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#integration

Registration:
Since version 1.x, this plugin no longer registers itself automatically. It must be manually registered either globally or locally

import ChartDataLabels from 'chartjs-plugin-datalabels';

// Register the plugin to all charts:
Chart.register(ChartDataLabels);

// OR only to specific charts:
var chart = new Chart(ctx, {
  plugins: [ChartDataLabels],
  options: {
    // ...
  }
})

Leave a comment