Chartjs-plugin-datalabels: Displaying custom labels from an array

Created on 15 Jan 2018  路  4Comments  路  Source: chartjs/chartjs-plugin-datalabels

I've got an array of data points, and another one of data label strings. I'm graphing the points and would like to use the strings as labels. How do I use this plugin to do so? Here's what I've got right now:

datasets: [{
  label: 'Phenological States',
  data: phenoArray(historicalData).values,
  datalabels: phenoArray(historicalData).labels,
  // ...
}]

Edit(SB): code formatting

documentation resolved support

Most helpful comment

I added some docs and a sample how to display custom labels (bea5b4be8dd99a4).

All 4 comments

It's possible, but dataset.datalabels is reserved for the plugin options so can't be used to store custom labels. You can either use the Chart.js built-in data.labels (category scale) or you can store them under whatever other unreserved name in the dataset (e.g. dataset.labels). Then you need to define a custom formatter and use context to reach your values.

If you use data.labels (fiddle):

new Chart('id', {
  data: {
    labels: phenoArray(historicalData).labels,
    datasets: [{
      label: 'Phenological States',
      data: phenoArray(historicalData).values
    }]
  },
  options: {
    plugins: {
      datalabels: {
        formatter: function(value, context) {
          return context.chart.data.labels[context.dataIndex];
        }
        // ... other options ...
      }
    }
  }
}

If you use dataset.labels (fiddle):

formatter: function(value, context) {
  return context.dataset.labels[context.dataIndex];
}

Thank you. I have many points in my graph-is there a value that I can pass so that only some of them are labeled? Something similar to autoskip and autoskip padding with scale options?

There isn't such feature built-in, you can make your own logic by scripting the display option:

options: {
  datalabels: {
    display: function(context) {
       // your logic here, return true to show a label, else false to hide
       // for example: display 1 label every 3 data
       return context.dataIndex % 3;
    }
  }
}

Of course it's way more complex to implement something similar to auto-skip. If you think that's a feature that makes sense, you can create a new ticket with a detailed description of the requirements and a jsfiddle that illustrates your problematic: that will help me to evaluate if we should and how to integrate that feature.

Did my previous comment solve your original issue?

I added some docs and a sample how to display custom labels (bea5b4be8dd99a4).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ed1nh0 picture ed1nh0  路  10Comments

EmilMoe picture EmilMoe  路  4Comments

012attack picture 012attack  路  8Comments

sidv93 picture sidv93  路  3Comments

wjohnsto picture wjohnsto  路  12Comments