Chartjs-Chartjs – Line between two dots on the Y axis

0👍

You can use a custom plugin for this:

const customLine = {
  id: 'customLine',
  beforeDatasetsDraw: (chart, args, options) => {
    const {
      ctx,
      scales: {
        x,
        y
      }
    } = chart;

    chart.data.datasets[0].data.forEach((dataPoint, i) => {

      ctx.strokeStyle = options.lineColor || 'black';
      ctx.lineWidth = options.lineWidth || 1;

      ctx.beginPath();
      ctx.moveTo(x.getPixelForValue(chart.data.labels[i]), y.getPixelForValue(dataPoint));
      ctx.lineTo(x.getPixelForValue(chart.data.labels[i]), y.getPixelForValue(chart.data.datasets[1].data[i]));
      ctx.stroke();

    })

  }
}

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1,
        showLine: false,
        backgroundColor: 'red'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1,
        showLine: false,
        backgroundColor: 'blue'
      }
    ]
  },
  options: {
    plugins: {
      customLine: {
        lineColor: 'pink',
        lineWidth: 3
      }
    }
  },
  plugins: [customLine]
}

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

Leave a comment