Chartjs-Cartesian coordinate system with chart.js

1👍

You can use the Plugin Core API that offers a range of hooks that may be used for performing custom code. In the beforeDraw for example, you can compute and set the ticks.padding of both axes in order to move the ticks to the desired position.

beforeDraw: chart => {
  var xAxis = chart.scales['x-axis-1'];
  var yAxis = chart.scales['y-axis-1'];
  const scales = chart.chart.config.options.scales;
  scales.xAxes[0].ticks.padding = yAxis.top - yAxis.getPixelForValue(0) + 6;
  scales.yAxes[0].ticks.padding = xAxis.getPixelForValue(0) - xAxis.right + 6;
}

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

new Chart('myChart', {
  type: 'scatter',
  plugins:[{
    beforeDraw: chart => {
      var xAxis = chart.scales['x-axis-1'];
      var yAxis = chart.scales['y-axis-1'];
      const scales = chart.chart.config.options.scales;
      scales.xAxes[0].ticks.padding = yAxis.top - yAxis.getPixelForValue(0) + 6;
      scales.yAxes[0].ticks.padding = xAxis.getPixelForValue(0) - xAxis.right + 6;
    }
  }],
  data: {
    datasets: [{
      label: 'Scatter Dataset',
      data: [{x:-3,y:5},{x:-2,y:0},{x:-1,y:-3},{x:0,y:-4},{x:1,y:-3},{x:2,y:0},{x:3,y:5}],
      borderColor: 'red'
    }]
  },
  options: {
    scales: {
      xAxes: [{
        ticks: {
          min: -6,
          max: 6,
          stepSize: 1,
          callback: v => v == 0 ? '' : v
        },
        gridLines: {
          drawTicks: false
        }        
      }],
      yAxes: [{
        ticks: {
          min: -6,
          max: 6,
          stepSize: 1,
          callback: v => v == 0 ? '' : v
        },
        gridLines: {
          drawTicks: false
        } 
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

Leave a comment