Chartjs-Chart js 2 bars with one customize label on top

1👍

You can use a custom plugin for that:

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: {
        name: 'ROI',
      }
    }
  },
  plugins: [{
    id: 'customValue',
    afterDraw: (chart, args, opts) => {
      const {
        ctx,
        data: {
          datasets
        },
        _metasets
      } = chart;

      datasets[0].data.forEach((dp, i) => {
        let barValue = `${(datasets[1].data[i] + dp) / 2}%`;
        const lineHeight = ctx.measureText('M').width;
        const textVal = opts.name || 'fill'

        ctx.textAlign = 'center';

        ctx.fillText(barValue, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 1.5), _metasets[0].data[i].width);
        ctx.fillText(textVal, _metasets[0].data[i].x, (_metasets[0].data[i].y - lineHeight * 3), _metasets[0].data[i].width);
      });
    }
  }]
}

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>

Leave a comment