Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Last active December 14, 2018 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clhenrick/da9301dc7f5304c6b2083ddcbc7e1baf to your computer and use it in GitHub Desktop.
Save clhenrick/da9301dc7f5304c6b2083ddcbc7e1baf to your computer and use it in GitHub Desktop.
scale sqrt vs scale linear
license: mit

Square Root vs. Linear Scale

On the left are circles sized using d3.scaleSqrt and the right are circles sized using d3.scaleLinear.

The same data (the numbers 20, 50, 150, 300) is used for each group of circles, but using a square root scale allows for mapping each data value to a circle's area, which is more perceptively correct for visualization purposes.

Built with blockbuilder.org

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
// adjust these values
var data = [20, 50, 150, 300];
var domain = [0, data[data.length - 1]];
var range = [0, 25];
var margin = {
top: 120,
left: 120,
right: 60,
bottom: 30
};
var svg = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500);
var height = svg.attr("height") - margin.top - margin.bottom;
var width = svg.attr("width") - margin.left - margin.right;
var sqrt = d3.scaleSqrt()
.range(range)
.domain(domain);
var linear = d3.scaleLinear()
.range(range)
.domain(domain);
var g = svg.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
g.selectAll(".sqrt")
.data(data)
.enter()
.append("circle")
.classed("sqrt", true)
.attr("cx", d => 0)
.attr("cy", d => -sqrt(d))
.attr("r", d => sqrt(d))
.attr("fill", "none")
.attr("stroke", "#000")
.attr("stroke-width", 0.7);
g.selectAll(".linear")
.data(data)
.enter()
.append("circle")
.classed("linear", true)
.attr("cx", d => 120)
.attr("cy", d => -linear(d))
.attr("r", d => linear(d))
.attr("fill", "none")
.attr("stroke", "#000")
.attr("stroke-width", 0.7);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment