Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active March 12, 2021 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save d3indepth/775cf431e64b6718481c06fc45dc34f9 to your computer and use it in GitHub Desktop.
Save d3indepth/775cf431e64b6718481c06fc45dc34f9 to your computer and use it in GitHub Desktop.
scaleSqrt example
license: gpl-3.0
height: 90
border: no

An example of a sqrtScale which is particularly useful for sizing circles by area.

From D3 in Depth book by Peter Cook.

<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>scaleSqrt example</title>
</head>
<style>
body {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 14px;
color: #333;
}
circle {
fill: #888;
}
</style>
<body>
<svg width="800" height="80">
<g id="wrapper" transform="translate(40, 40)">
</g>
</svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
var linearScale = d3.scaleLinear()
.domain([0, 100])
.range([0, 700]);
var sqrtScale = d3.scaleSqrt()
.domain([0, 100])
.range([0, 30]);
var myData = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
d3.select('#wrapper')
.selectAll('circle')
.data(myData)
.enter()
.append('circle')
.attr('r', function(d) {
return sqrtScale(d);
})
.attr('cx', function(d) {
return linearScale(d);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment