forked from sgratzl/d3tutorial
-
Notifications
You must be signed in to change notification settings - Fork 5
/
choropleth.html
81 lines (73 loc) · 2.51 KB
/
choropleth.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>US Choropleth Map</title>
<meta name="description" content="force directed graph example" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
<script src="../web_modules/d3/dist/d3.js"></script>
<script src="https://cdn.jsdelivr.net/npm/topojson-client"></script>
<link href="./style.css" rel="stylesheet" />
<style>
path {
stroke: #999;
}
path:hover {
stroke: black;
}
</style>
</head>
<body>
<h1>US Choropleth Map</h1>
<script>
const margin = {
top: 10,
bottom: 10,
left: 10,
right: 10,
};
const width = 800 - margin.left - margin.right;
const height = 600 - margin.top - margin.bottom;
// Creates sources <svg> element and inner g (for margins)
const svg = d3
.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
/////////////////////////
const projection = d3.geoAlbersUsa();
const path = d3.geoPath(projection);
const color = d3.scaleSequential(d3.interpolateBlues);
d3.json("https://cdn.jsdelivr.net/npm/us-atlas/states-10m.json").then((us) => {
const states = topojson.feature(us, us.objects.states).features;
const nation = topojson.feature(us, us.objects.nation).features[0];
// scale to fit bounds
projection.fitSize([width, height], nation);
const data = states.map((feature) => ({
feature: feature,
name: feature.properties.name,
value: Math.random(), // random value
}));
const paths = svg
.selectAll("path")
.data(data)
.join((enter) => {
const p = enter.append("path");
p.on("mouseenter", function () {
// move the SVG element after all other elements to be on the top
d3.select(this).raise();
});
p.append("title");
return p;
})
.attr("d", (d) => path(d.feature))
.style("fill", (d) => color(d.value));
paths.select("title").text((d) => d.name);
});
</script>
</body>
</html>