Chartjs-Chartjs horizontal line between bars instead of top to top

1👍

I think you need a custom plugin to do that.

Below snippet a prototype:

const plugin = {
  id: 'lineToBar',
  afterDraw(chart) {
    const ctx = chart.ctx;
    const meta = chart.getDatasetMeta(0);
    const data = meta.data;
    const count = data.length;
    ctx.save();
    ctx.lineWidth = 2;
    for (let i = 0; i<(count-1); i++) {
      const k = i + 1;
      const from = data[i];
      const x = from.x + from.width /2;
      const to = data[k];
      const x2 = to.x - to.width / 2;
      ctx.strokeStyle = from.options.backgroundColor;
      ctx.beginPath();
      ctx.moveTo(x, from.y + ctx.lineWidth / 2);
      ctx.lineTo(x2, from.y + ctx.lineWidth / 2);
      if (from.y < to.y) {
        ctx.lineTo(x2, to.y);
      }
      ctx.stroke();
    }
    const last = data[count-1];
    const area = chart.chartArea;
    ctx.strokeStyle = last.options.backgroundColor;
    ctx.beginPath();
    ctx.moveTo(last.x + last.width /2, last.y + ctx.lineWidth / 2);
    ctx.lineTo(area.right, last.y + ctx.lineWidth / 2);
    ctx.stroke();
    ctx.restore();
  }
};
const labels2 = ["A", "B", "C", "D", "E", "F", "G"];
const config2 = {
  type: 'bar',
  plugins: [plugin],
  data: {
    labels: labels2,
    datasets: [{
      label: 'ds',
      data: labels2.map(() => Math.random() * 100)
    }]
  },
  options: {
  }
};
const chart = new Chart(
  document.getElementById('myChart'),
  config2
);
document.getElementById("randomize").addEventListener('click', function() {
  const data = labels2.map(() => Math.random() * 100);
  chart.data.datasets[0].data = data;
  chart.update();
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<html>
  <head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.2.1/dist/chart.umd.min.js"></script>
  </head>  
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600px" height="400px"/>
    </div>
    <button id="randomize">Randomize</button>
  </body>
</html>

Leave a comment