Chartjs-References in axis using chart.js (or another library)

1👍

Unfortunately, there is no native support in chart.js for what you are wanting. However, you can certainly add this capability using the plugin interface. This requires that you implement your own logic to draw the canvas pixels at the locations that you want them. It might sound challenging, but its easier than it sounds.

Here is an example plugin that will add a value above specific points in the chart (based upon configuration).

Chart.plugins.register({
  afterDraw: function(chartInstance) {
    if (chartInstance.config.options.showDatapoints || chartInstance.config.options.showDatapoints.display) {
      var showOnly = chartInstance.config.options.showDatapoints.showOnly || [];
      var helpers = Chart.helpers;
      var ctx = chartInstance.chart.ctx;
      var fontColor = helpers.getValueOrDefault(chartInstance.config.options.showDatapoints.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) {
        for (var i = 0; i < dataset.data.length; i++) {
          if (showOnly.includes(dataset.data[i])) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
            var scaleMax = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
            var yPos = (scaleMax - model.y) / scaleMax >= 0.93 ? model.y + 20 : model.y - 5;
            ctx.fillText(dataset.data[i], model.x, yPos);
          }
        }
      });
    }
  }
});

It allows you to configure which points you want to annotate using this new configuration. The showOnly option contains the points that you want to label.

options: {
  showDatapoints: {
    display: true,
    showOnly: [3, 10, 9]
  },
}

Obviously, this only adds the datapoint value at the specified points, but you can just change the plugin to paint whatever you want to show instead. Simply replace ctx.fillText(dataset.data[i], model.x, yPos) with different code to render something different on the canvas.

Here is a codepen example to show you want it looks like.

Leave a comment