Chartjs-How to make custom text appear underneath each bar in chartjs bar chart?

1👍

I don’t exactly understand why you want to repeat the labels on the xAxes but this can be done with the Plugin Core API. The API offers different hooks that may be used for executing custom code. In your case, you can use the afterDraw hook to draw text directly on the canvas.

The plugin would be defined as follows:

const plugins = [{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    var xAxis = chart.scales["x-axis-0"];
    var yAxis = chart.scales["y-axis-0"];
    xAxis.ticks.forEach((v, i) => {
      var x = xAxis.getPixelForTick(i);
      var value = chart.data.datasets[0].data[i];
      ctx.textAlign = "center";
      ctx.font = "18px Arial";
      ctx.fillStyle = value < 0 ? "#fc3e78" : "#53b300";
      ctx.fillText(value, x, yAxis.bottom + 80);
      ctx.fillText(likeslabels[i][0], x, yAxis.bottom + 100);
    });
    ctx.restore();
  }
}];

Then tell the Bar element about the plugin to be used.

<Bar
      ref={barRef}
      data={likesdata}
      plugins={plugins}  // add this line
      width={75}
      height={20}
      options={likesoptions}
/>

Also add some extra space at the bottom of the chart by defining layout.padding.bottom inside the chart options, otherwise the text won’t be visible.

const likesoptions = {
  layout: {
    padding: {
      bottom: 60
    }
  },

Please have a look at your amended CodeSandbox.

Leave a comment