forked from zeroviscosity/d3-js-step-by-step
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstep-3-adding-a-legend.html
91 lines (80 loc) · 3.53 KB
/
step-3-adding-a-legend.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
80
81
82
83
84
85
86
87
88
89
90
91
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Step 3 - Adding a Legend</title>
<link rel="stylesheet" href="normalize.css">
<style>
.legend { /* NEW */
font-size: 12px; /* NEW */
} /* NEW */
rect { /* NEW */
stroke-width: 2; /* NEW */
} /* NEW */
</style>
</head>
<body>
<div id="chart"></div>
<script src="d3.v4.min.js"></script>
<script>
(function(d3) {
'use strict';
var dataset = [
{ label: 'Abulia', count: 10 },
{ label: 'Betelgeuse', count: 20 },
{ label: 'Cantaloupe', count: 30 },
{ label: 'Dijkstra', count: 40 }
];
var width = 360;
var height = 360;
var radius = Math.min(width, height) / 2;
var donutWidth = 75;
var legendRectSize = 18; // NEW
var legendSpacing = 4; // NEW
var color = d3.scaleOrdinal(d3.schemeCategory20b);
var svg = d3.select('#chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var arc = d3.arc()
.innerRadius(radius - donutWidth)
.outerRadius(radius);
var pie = d3.pie()
.value(function(d) { return d.count; })
.sort(null);
var path = svg.selectAll('path')
.data(pie(dataset))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color(d.data.label);
});
var legend = svg.selectAll('.legend') // NEW
.data(color.domain()) // NEW
.enter() // NEW
.append('g') // NEW
.attr('class', 'legend') // NEW
.attr('transform', function(d, i) { // NEW
var height = legendRectSize + legendSpacing; // NEW
var offset = height * color.domain().length / 2; // NEW
var horz = -2 * legendRectSize; // NEW
var vert = i * height - offset; // NEW
return 'translate(' + horz + ',' + vert + ')'; // NEW
}); // NEW
legend.append('rect') // NEW
.attr('width', legendRectSize) // NEW
.attr('height', legendRectSize) // NEW
.style('fill', color) // NEW
.style('stroke', color); // NEW
legend.append('text') // NEW
.attr('x', legendRectSize + legendSpacing) // NEW
.attr('y', legendRectSize - legendSpacing) // NEW
.text(function(d) { return d; }); // NEW
})(window.d3);
</script>
</body>
</html>