score:1

Accepted answer

you are best off using a custom inline plugin for this:

var options = {
  type: 'bar',
  data: {
    labels: ["red", "blue", "yellow", "green", "purple", "orange"],
    datasets: [{
        label: '# of votes',
        data: [12, 19, 3, 5, 2, 3],
        backgroundcolor: 'red'
      },
      {
        label: '# of points',
        data: [7, 11, 5, 8, 3, 7],
        backgroundcolor: 'blue'
      }
    ]
  },
  options: {
    plugins: {
      customvalue: {
        offset: 5,
        dash: [5, 15]
      }
    }
  },
  plugins: [{
    id: 'customvalue',
    afterdraw: (chart, args, opts) => {
      const {
        ctx,
        data: {
          datasets
        },
        _metasets
      } = chart;

      datasets[1].data.foreach((dp, i) => {
        let increasepercent = dp * 100 / datasets[0].data[i] >= 100 ? math.round((dp * 100 / datasets[0].data[i] - 100) * 100) / 100 : math.round((100 - dp * 100 / datasets[0].data[i]) * 100) / 100 * -1;
        let barvalue = `${increasepercent}%`;
        const lineheight = ctx.measuretext('m').width;
        const offset = opts.offset || 0;
        const dash = opts.dash || [];

        ctx.textalign = 'center';

        ctx.filltext(barvalue, _metasets[1].data[i].x, (_metasets[1].data[i].y - lineheight * 1.5), _metasets[1].data[i].width);

        if (_metasets[0].data[i].y >= _metasets[1].data[i].y) {
          ctx.beginpath();
          ctx.setlinedash(dash);

          ctx.moveto(_metasets[0].data[i].x, _metasets[0].data[i].y);
          ctx.lineto(_metasets[0].data[i].x, _metasets[1].data[i].y - offset);
          ctx.lineto(_metasets[1].data[i].x, _metasets[1].data[i].y - offset);
          ctx.stroke();
        } else {
          ctx.beginpath();
          ctx.setlinedash(dash);

          ctx.moveto(_metasets[0].data[i].x, _metasets[0].data[i].y - offset);
          ctx.lineto(_metasets[1].data[i].x, _metasets[0].data[i].y - offset);
          ctx.lineto(_metasets[1].data[i].x, _metasets[1].data[i].y - offset - lineheight * 2);
          ctx.stroke();
        }
      });
    }
  }]
}

var ctx = document.getelementbyid('chartjscontainer').getcontext('2d');
new chart(ctx, options);
<body>
  <canvas id="chartjscontainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/3.4.1/chart.js"></script>
</body>


Related Query

More Query from same tag