Chartjs-Style Chart.js floating bar chart

2๐Ÿ‘

โœ…

I think there are 2 options:

  1. use Chart error bars plugin: https://github.com/sgratzl/chartjs-chart-error-bars
  2. develop own plugin to do that.

In the below snippet, you can find the options 2 (own plugin)

var plugin = {
  id: 'myPlugin',
  afterDraw(chart, args) {
    const ctx  = chart.ctx;
    ctx.save();
    const meta = chart.getDatasetMeta(0);
    for (const data of meta.data) {
      const topStart = data.x - 20;
      const topEnd = data.x + 20;
      ctx.lineWidth  = data.options.borderWidth;
      ctx.strokeStyle = data.options.backgroundColor;
      ctx.beginPath();
      ctx.moveTo(topStart, data.y);
      ctx.lineTo(topEnd, data.y);
      ctx.moveTo(topStart, data.y + data.height);
      ctx.lineTo(topEnd, data.y + data.height);
      ctx.closePath();
      ctx.stroke();
    }
    ctx.restore();
  }
};
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    plugins: [plugin],
    data: {
        datasets: [{
            label: 'Range',
            data: [
              {x: 'A', y: [100, 200]},
              {x: 'B', y: [50, 120]}
            ],
          backgroundColor: ['red']
        }]
    },
    options: {
      barThickness: 1,
    }
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://npmcdn.com/chart.js@latest/dist/chart.min.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

Leave a comment