[Chartjs]-Chart JS pass in custom data for points

1👍

I would just define some configuration properties for your new plugin and use one of those properties to define where the point reference should be located and what the reference value should be.

Here is an example of what I mean. This would be in the chart’s options property.

pointReferenceLetters: {
  display: true,
  fontColor: 'green',
  references: [
    {datasetIndex: 0, dataIndex: 1, reference: 'A'},
    {datasetIndex: 1, dataIndex: 2, reference: 'B'},
  ]
}

The plugin would then use this data to draw the point references. Here is an example showing how a plugin would use this data. Note, I just did a quick implementation to show the concept, this plugin does not draw the reference circle like yours would.

Chart.plugins.register({
  afterDraw: function(chartInstance) {
    if (chartInstance.config.options.pointReferenceLetters || chartInstance.config.options.pointReferenceLetters.display) {
      var references = chartInstance.config.options.pointReferenceLetters.references || [];
      var helpers = Chart.helpers;
      var ctx = chartInstance.chart.ctx;
      var fontColor = helpers.getValueOrDefault(chartInstance.config.options.pointReferenceLetters.fontColor, chartInstance.config.options.defaultFontColor);

      // render the value of the chart above the bar
      ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize + 5, 'normal', Chart.defaults.global.defaultFontFamily);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'bottom';
      ctx.fillStyle = fontColor;

      chartInstance.data.datasets.forEach(function (dataset, dsindex) {
        for (var i = 0; i < dataset.data.length; i++) {
          // note, many browsers don't support the array.find() function.
          // if you use this then be sure to provide a pollyfill
          var refPoint = references.find(function(e) {
            return e.datasetIndex == dsindex && e.dataIndex === i
          });

          if (refPoint) {         
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            ctx.fillText(refPoint.reference, model.x, model.y + 30);
          }
        }
      });
    }
  }
});

As you an see, the plugin uses the data provided in the pointReferenceLetters.references property to determine when a point reference should be drawn and then uses the values provided as the reference text.

Here is a codepen example that demonstrates all of this.

Leave a comment