JSFiddle - React, Tailwind, and code Playground

by tonyleeper

JavaScript

// given a dataset, choose suitable tick values for the axis of a scatter graph
var data = [
    { x: -1, y: 10 },
    { x: 2, y: 132340 },
    { x: 2.4, y: 12340 },
    { x: 3, y: 10234 },
    { x: -5, y: -1034 },
    { x: 6, y: 11110 },
    { x: 12, y: 103423 },
    { x: 17, y: 10234 },
    { x: 34, y: 234 }
];

function getTickDelta (maxValue, ticks) {
    var delta = maxValue / ticks;
    var log10 = Math.log(delta) / Math.log(10);
    var tickDelta = Math.pow(10, Math.ceil(log10));  
    
    if (tickDelta * ticks > maxValue * 2) {
    	return tickDelta / 2;
    } else {
    	return tickDelta;
    }
}

var minX = data.reduce(function (prev, next) { return { x: Math.min(prev.x, next.x) }; }).x;
var maxX = data.reduce(function (prev, next) { return { x: Math.max(prev.x, next.x) }; }).x;

var minY = data.reduce(function (prev, next) { return { y: Math.min(prev.y, next.y) }; }).y;
var maxY = data.reduce(function (prev, next) { return { y: Math.max(prev.y, next.y) }; }).y;

var axisDefinitions = {
	x: {
    	min: minX,
    	max: maxX,
        ticks: 7,
        tickDelta: getTickDelta(maxX - Math.min(minX, 0), 7)
    },
    y: {
    	min: minY,
    	max: maxY,
        ticks: 7,
        tickDelta: getTickDelta(maxY - Math.min(minY, 0), 7)
    }
}

console.log(axisDefinitions);