[Chartjs]-Chart.js: Can't get a coordinate for value for x axis unless x axis has the exact same value

2👍

When the data is an array of numbers, the x-axis is generally a category. The points are placed onto the axis using their position in the array, which should also match a value from labels.

Yo need to change the x-axis into linear type in order to obtain correct values from the function getPixelForValue.

  1. Don’t define labels
  2. Define the data as an array of points using objects containing x and y properties each.
  3. Add type: 'linear' to the xAxes option

Please take a look at your amended code and see how it works.

new Chart("chart", {
  type: 'line',
  plugins: [{
    beforeDraw: (chart) => {
      console.log(chart.scales['y-axis-0'].getPixelForValue(23.56));
      console.log(chart.scales['x-axis-0'].getPixelForValue(36.98));
      console.log(chart.scales['x-axis-0'].getPixelForValue(40));
    }
  }],
  data: {
    datasets: [{
      label: '',
      data: [
        { x: 10, y:34 },
        { x: 20, y:56 },
        { x: 30, y:78 },
        { x: 40, y:12 },
        { x: 50, y:45 },
        { x: 60, y:67 },
        { x: 70, y:12 },
        { x: 80, y:89 },
        { x: 90, y:93 },
        { x: 100, y:43 }],
      type: 'line',
      borderColor: 'red',
      fill: false,
      lineTension: 0,
    }],
  },
  options: {
    responsive: true,
    scales: {
      xAxes: [{ 
        type: 'linear',
        scaleLabel: {
          display: true,
          labelString: 'x',
        }
      }],
      yAxes: [{
        ticks: {          
          beginAtZero: true,
          stepSize: 10,
          suggestedMax: 100,
        },
        scaleLabel: {
          display: true,
          labelString: 'y',
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="200"></canvas>

Leave a comment