Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Style Chart.js floating bar chart

I’ve created a chart in Chart.js that looks like this:

enter image description here

(Full code: https://codepen.io/LondonAppDev/pen/RwMBxPX)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        datasets: [{
            label: 'Range',
            data: [
              {x: 'A', y: [100, 200]},
              {x: 'B', y: [50, 120]}
            ],
          backgroundColor: ['red']
        }]
    },
    options: {
      barThickness: 1,
    }
});

I’m trying to style the bar so they have markers at the top and bottom like this:

enter image description here

I’ve looked into CSS but it won’t work as the elements are within a canvas.

I’m wondering if there is a style option that would achieve this?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading