[Chartjs]-"Inline" labels in ChartJS

1👍

You can use chartjs-plugin-datalabels for this which is very useful when displaying labels on data for any type of charts and is highly customizable.

Note that this requires Chart.js 2.7.0 or later.

Use it by including it under the plugins key of your chart options as shown in the following solutions below.


Solution #1.

The configuration below will display your labels on the top center of each bar. See working example.

var options = {
  plugins: {
    datalabels: {
      // use the formatter function to customize the labels displayed
      formatter: function(value, context) {
        return context.chart.data.labels[context.dataIndex];
      },
      align: "top",
      anchor: "center",
      offset: 25,
      padding: -2,
      clip: true,
      font: {
        size: "16",
        weight: "bold"
      }
    }
  }
};

However, this is not exactly like the screenshot you provided so,

Solution #2.

Here’s one workaround I can suggest to replicate the exact behaviour that you want.

  • anchor: 'start' and align: -60: that will bring your data label on top, left aligned

  • make your chart start at zero by setting scale.ticks.beginAtZero to true

  • offset: 25: distance (in pixels) to pull the label away from the anchor point

  • padding: function() {}: use a scriptable option to dynamically compute the left padding based on the label approximate size since adding a specific padding will only work if your labels have the same width that doesn’t change which is not this case

See working example for a detailed overview of the configurations.

This solution will work but it’s definitely not ideal since the
position of these labels may change depending on the label size, bar
thickness, and the size of the chart.

Leave a comment