How to get a square grid in Chart.js with responsive scatter chart?

๐Ÿ‘:0

You can use the scriptable options to calculate the amount of ticks you need with a given spacing to get squares, it need some fine tuning because of rounding but this will give you a rough idea/setup to finetune

Example:

const spacing = 50;

var options = {
  type: 'scatter',
  data: {
    datasets: [{
        label: '# of Votes',
        data: [{
          x: 0,
          y: 4
        }, {
          x: 2,
          y: 2
        }, {
          x: 4,
          y: 0
        }],
        borderWidth: 1,
        backgroundColor: 'blue'
      },
      {
        label: '# of Points',
        data: [{
          x: 2,
          y: 3
        }, {
          x: 6,
          y: 8
        }, {
          x: 0,
          y: 3
        }],
        borderWidth: 1,
        backgroundColor: 'red'
      }
    ]
  },
  options: {
    scales: {
      y: {
        ticks: {
          count: (ctx) => {
            const {
              scale: {
                maxHeight
              }
            } = ctx;

            return maxHeight / spacing;
          }
        }
      },
      x: {
        ticks: {
          count: (ctx) => {
            const {
              scale: {
                maxWidth
              }
            } = ctx;

            return maxWidth / spacing;
          }
        }
      }
    }
  }
}

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

Leave a comment