Sunburst
Sunburst design by John Stasko. Data courtesy Jeff Heer.
Source Code
1 var w = 960,
2 h = 700,
3 r = Math.min(w, h) / 2,
4 color = d3.scale.category20c();
5
6 var vis = d3.select("#chart").append("svg:svg")
7 .attr("width", w)
8 .attr("height", h)
9 .append("svg:g")
10 .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");
11
12 var partition = d3.layout.partition()
13 .sort(null)
14 .size([2 * Math.PI, r * r])
15 .children(function(d) { return isNaN(d.value) ? d3.entries(d.value) : null; })
16 .value(function(d) { return 1; });
17
18 var arc = d3.svg.arc()
19 .startAngle(function(d) { return d.x; })
20 .endAngle(function(d) { return d.x + d.dx; })
21 .innerRadius(function(d) { return Math.sqrt(d.y); })
22 .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });
23
24 d3.json("flare.json", function(json) {
25 vis.data(d3.entries(json)).selectAll("path")
26 .data(partition)
27 .enter().append("svg:path")
28 .attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
29 .attr("d", arc)
30 .attr("stroke", "#fff")
31 .attr("fill", function(d) { return color((d.children ? d : d.parent).data.key); })
32 .attr("fill-rule", "evenodd");
33
34 d3.select("#size").on("click", function() {
35 vis.selectAll("path")
36 .data(repartition(function(d) { return d.value; }))
37 .transition()
38 .duration(1500)
39 .attrTween("d", arcTween);
40
41 d3.select("#size").classed("active", true);
42 d3.select("#count").classed("active", false);
43 });
44
45 d3.select("#count").on("click", function() {
46 vis.selectAll("path")
47 .data(repartition(function(d) { return 1; }))
48 .transition()
49 .duration(1500)
50 .attrTween("d", arcTween);
51
52 d3.select("#size").classed("active", false);
53 d3.select("#count").classed("active", true);
54 });
55 });
56
57 // Compute a new partition, stashing the old value for transition.
58 function repartition(value) {
59 return function(d) {
60 var olds = partition(d),
61 news = partition.value(value)(d);
62 news.forEach(function(d, i) {
63 d.prev = olds[i];
64 });
65 return news;
66 };
67 }
68
69 // Interpolate the arcs in data space.
70 function arcTween(a) {
71 var i = d3.interpolate({x: a.prev.x, dx: a.prev.dx}, a);
72 return function(t) {
73 return arc(i(t));
74 };
75 }