This repository has been archived by the owner on Apr 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcartogram.html
90 lines (79 loc) · 2.32 KB
/
cartogram.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
<!DOCTYPE html>
<meta charset="utf-8">
<title>Non-Contiguous Cartogram</title>
<style>
.land {
fill: #fff;
stroke: #ccc;
}
.state {
stroke: #777;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
// Ratio of Obese (BMI >= 30) in U.S. Adults, CDC 2008
var valueById = [
NaN, .187, .198, NaN, .133, .175, .151, NaN, .100, .125,
.171, NaN, .172, .133, NaN, .108, .142, .167, .201, .175,
.159, .169, .177, .141, .163, .117, .182, .153, .195, .189,
.134, .163, .133, .151, .145, .130, .139, .169, .164, .175,
.135, .152, .169, NaN, .132, .167, .139, .184, .159, .140,
.146, .157, NaN, .139, .183, .160, .143
];
d3.csv('normalized_state_crime.csv', function (err, data) {
console.log('data!', data)
var valuesByState = {}
var values = data.forEach(function(data) {
valuesByState[data.Code] = data
})
function fillFn (d) {
var data = valuesByState[d.id]
if (!data) {
console.log('could not get data for', d)
return '#F36866'
}
var statutes = ~~data.Statutes
if (statutes === 2) {
return '#2ca02c'
} else if (statutes === 1) {
return '#98df8a'
} else {
return '#F36866'
}
}
var svg = d3.select("body").append("svg")
.attr("width", 1200)
.attr("height", 675);
var path = d3.geo.path();
d3.json("us.topo.json", function(error, us) {
if (error) throw error;
svg.append("path")
.datum(topojson.feature(us, us.objects.usa))
.attr("class", "land")
.attr("d", path);
svg.selectAll(".state")
.data(topojson.feature(us, us.objects.usa).features)
.enter().append("path")
.attr("class", "state")
.attr("d", path)
.attr("fill", fillFn)
.attr("transform", function(d) {
if (!valuesByState[d.id]) {
console.log('could not get data for', d)
return
}
var scale = Math.sqrt(parseFloat(valuesByState[d.id].Normalized) / 5)
console.log(valuesByState[d.id].Code, scale)
var centroid = path.centroid(d),
x = centroid[0],
y = centroid[1];
return "translate(" + x + "," + y + ")"
+ "scale(" + scale + ")"
+ "translate(" + -x + "," + -y + ")";
})
});
});
</script>