How to create range based ticks in chart js? (like in attached image)

1👍

You can use the plugin api to draw anything you want on the canvas:

const customPlugin = {
  id: 'customTicks',
  afterDraw: (chart, args, opts) => {
    if (opts.ticks === undefined) {
      return
    }

    const {
      ctx,
      canvas,
      scales: {
        x,
        y
      }
    } = chart;
    const {
      ticks,
      offset,
      textColor,
      fontString
    } = opts;
    const xStart = x.getPixelForValue(x.ticks[x.ticks.length - 1].value) + (offset || 0);
    const width = canvas.width - xStart;

    ticks.forEach((tick) => {
      ctx.save();
      ctx.fillStyle = tick.color;
      ctx.fillRect(xStart, y.getPixelForValue(tick.from), width, (y.getPixelForValue(tick.to) - y.getPixelForValue(tick.from)));

      ctx.fillStyle = textColor || 'black';
      ctx.textAlign = "center";
      ctx.font = fontString || '12px "Helvetica Neue", Helvetica, Arial, sans-serif'

      ctx.translate(xStart + width / 2, (y.getPixelForValue(tick.to) + y.getPixelForValue(tick.from)) / 2)
      ctx.rotate(-Math.PI / 2);
      ctx.fillText(tick.text, 0, 0)
      ctx.restore();
    })
  }
}

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'pink'
    }]
  },
  options: {
    layout: {
      padding: {
        right: 60 // Add padding on the right for the ticks to draw
      }
    },
    plugins: {
      customTicks: {
        offset: 10, // Distance between the boxes and the chartArea
        textColor: 'white',
        fontString: "30px Comic Sans MS",
        ticks: [{
            from: 2,
            to: 6,
            color: 'red',
            text: 'Low'
          },
          {
            from: 6,
            to: 12,
            color: 'green',
            text: 'Medium'
          },
          {
            from: 12,
            to: 20,
            color: 'red',
            text: 'High'
          }
        ]
      }
    }
  },
  plugins: [customPlugin]
}

const 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.5.0/chart.js"></script>
</body>

Leave a comment