-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpie.js
78 lines (56 loc) · 1.83 KB
/
pie.js
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
function createPie(width, height) {
var pie = d3.select("#pie")
.attr("width", width)
.attr("height", height);
pie.append("g")
.attr("transform", "translate(" + width / 2 + ", " + (height / 2 + 10) + ")")
.classed("chart", true);
pie.append("text")
.attr("x", width / 2)
.attr("y", "1em")
.attr("font-size", "1.5em")
.style("text-anchor", "middle")
.classed("pie-title", true);
}
function drawPie(data, currentYear) {
var pie = d3.select("#pie");
var arcs = d3.pie()
.sort((a,b) => {
if (a.continent < b.continent) return -1;
if (a.continent > b.continent) return 1;
return a.emissions - b.emissions;
})
.value(d => d.emissions);
var path = d3.arc()
.outerRadius(+pie.attr("height") / 2 - 50)
.innerRadius(0);
var yearData = data.filter(d => d.year === currentYear);
var continents = [];
for (var i = 0; i < yearData.length; i++) {
var continent = yearData[i].continent;
if (!continents.includes(continent)) {
continents.push(continent);
}
}
var colorScale = d3.scaleOrdinal()
.domain(continents)
.range(["#ab47bc", "#7e57c2", "#26a69a", "#42a5f5", "#78909c"]);
var update = pie
.select(".chart")
.selectAll(".arc")
.data(arcs(yearData));
update
.exit()
.remove();
update
.enter()
.append("path")
.classed("arc", true)
.attr("stroke", "#dff1ff")
.attr("stroke-width", "0.25px")
.merge(update)
.attr("fill", d => colorScale(d.data.continent))
.attr("d", path);
pie.select(".pie-title")
.text("Total emissions by continent and region, " + currentYear);
}