Skip to content

Instantly share code, notes, and snippets.

@maybelinot
Last active September 2, 2021 07:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save maybelinot/5552606564ef37b5de7e47ed2b7dc099 to your computer and use it in GitHub Desktop.
Save maybelinot/5552606564ef37b5de7e47ed2b7dc099 to your computer and use it in GitHub Desktop.
Zoomable Sunburst on d3.js v4
license: gpl-3.0

I and Serhii Pahuta rewrote Mike Bostock's Zoomable Sunburst to newer version 4 of d3.js library. All functionality remains the same.

Click on any arc to zoom in, and click on the center circle to zoom out. Permanent link.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke: #fff;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 700,
radius = (Math.min(width, height) / 2) - 10;
var formatNumber = d3.format(",d");
var x = d3.scaleLinear()
.range([0, 2 * Math.PI]);
var y = d3.scaleSqrt()
.range([0, radius]);
var color = d3.scaleOrdinal(d3.schemeCategory20);
var partition = d3.partition();
var arc = d3.arc()
.startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x0))); })
.endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x1))); })
.innerRadius(function(d) { return Math.max(0, y(d.y0)); })
.outerRadius(function(d) { return Math.max(0, y(d.y1)); });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + (height / 2) + ")");
d3.json("https://gist.githubusercontent.com/mbostock/4348373/raw/85f18ac90409caa5529b32156aa6e71cf985263f/flare.json", function(error, root) {
if (error) throw error;
root = d3.hierarchy(root);
root.sum(function(d) { return d.size; });
svg.selectAll("path")
.data(partition(root).descendants())
.enter().append("path")
.attr("d", arc)
.style("fill", function(d) { return color((d.children ? d : d.parent).data.name); })
.on("click", click)
.append("title")
.text(function(d) { return d.data.name + "\n" + formatNumber(d.value); });
});
function click(d) {
svg.transition()
.duration(750)
.tween("scale", function() {
var xd = d3.interpolate(x.domain(), [d.x0, d.x1]),
yd = d3.interpolate(y.domain(), [d.y0, 1]),
yr = d3.interpolate(y.range(), [d.y0 ? 20 : 0, radius]);
return function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); };
})
.selectAll("path")
.attrTween("d", function(d) { return function() { return arc(d); }; });
}
d3.select(self.frameElement).style("height", height + "px");
</script>
@mablatnik
Copy link

This is really great. Thanks for putting the conversion together. Do know of a way to add labels to the sectors?

@COLTstreet
Copy link

I've successfully added labels, but they don't work with the transitions. Is there an example of this anywhere?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment