forked from barryclark/jekyll-now
/
sunburst-3.html
79 lines (68 loc) · 2.67 KB
/
sunburst-3.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!DOCTYPE html>
<head>
<title>Sunburst Tutorial (d3 v4), Part 3</title>
<script src='../plugins/d3/d3.v4.min.js'></script>
<!-- Want to run locally? Update src: 'https://d3js.org/d3.v4.min.js' -->
</head>
<body>
<svg></svg>
</body>
<script>
var vWidth = 300;
var vHeight = 300;
var vRadius = Math.min(vWidth, vHeight) / 2;
var vColor = d3.scaleOrdinal(d3.schemeCategory20b.slice(11));
// Prepare our physical space
var g = d3.select('svg')
.attr('width', vWidth).attr('height', vHeight)
.append('g')
.attr('transform', 'translate(' + vWidth / 2 + ',' + vHeight / 2 + ')');
// Declare d3 layout
var vLayout = d3.partition().size([2 * Math.PI, vRadius]);
var vArc = d3.arc()
.startAngle(function (d) { return d.x0; })
.endAngle(function (d) { return d.x1; })
.innerRadius(function (d) { return d.y0; })
.outerRadius(function (d) { return d.y1; });
// Get the data from our JSON file
d3.json('data-simple.json', function(error, vData) {
if (error) throw error;
drawSunburst(vData);
});
/**
* Draw our sunburst
* @param {object} data - Hierarchical data
*/
function drawSunburst(data) {
// Layout + Data
var vRoot = d3.hierarchy(data).sum(function (d) { return d.size});
var vNodes = vRoot.descendants();
vLayout(vRoot);
var vSlices = g.selectAll('g').data(vNodes).enter().append('g');
// Draw on screen
vSlices.append('path')
.attr('display', function (d) { return d.depth ? null : 'none'; })
.attr('d', vArc)
.style('stroke', '#fff')
.style('fill', function (d) { return vColor((d.children ? d : d.parent).data.id); });
// Add text
vSlices.append('text')
.filter(function(d) { return d.parent; })
.attr('transform', function(d) {
return 'translate(' + vArc.centroid(d) + ') rotate(' + computeTextRotation(d) + ')'; })
.attr('dx', '-20')
.attr('dy', '.5em')
.text(function(d) { return d.data.id });
}
/**
* Calculate the rotation for each label based on its location in the sunburst.
* @param {Node} d - the d3 note for which we're computing text rotation
* @return {Number} the value that should populate the transform: rotate() statement
*/
function computeTextRotation(d) {
var angle = (d.x0 + d.x1) / Math.PI * 90;
// Avoid upside-down labels
return (angle < 120 || angle > 270) ? angle : angle + 180; // labels as rims
//return (angle < 180) ? angle - 90 : angle + 90; // labels as spokes
}
</script>