-
Notifications
You must be signed in to change notification settings - Fork 6
/
choropleth.js
421 lines (389 loc) · 15.7 KB
/
choropleth.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
(function(){
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function Set() {
this.content = {};
}
Set.prototype.add = function(val) {
this.content[val]=true;
}
Set.prototype.remove = function(val) {
delete this.content[val];
}
Set.prototype.contains = function(val) {
return (val in this.content);
}
Set.prototype.asArray = function() {
var res = [];
for (var val in this.content) res.push(val);
return res;
}
var svg;
var path;
var data;
var jsonCache = {};
function loadCacheJson(url, callback) {
if(url in jsonCache) {
if(jsonCache[url].loaded)
callback(jsonCache[url].json);
else
jsonCache[url].callbacks.push(callback);
return;
}
jsonCache[url] = {
json: undefined,
loaded: false,
callbacks: [callback]
};
d3.json(url, function(json) {
jsonCache[url].json = json;
jsonCache[url].loaded = true;
jsonCache[url].callbacks.reverse().forEach(function(c) { c(json); });
delete jsonCache[url].callbacks;
});
}
function init() {
/* Projection centrée sur la France */
var xy = d3.geo.albers()
.origin([2.6,46.5])
.parallels([44,49])
.scale(2700)
.translate([250,250]);
path = d3.geo.path().projection(xy);
data = {};
data.departement = {};
data.departement.properties = new Set();
data.arrondissement = {};
data.arrondissement.properties = new Set();
data.canton = {};
data.canton.properties = new Set();
data.commune = {};
data.commune.properties = new Set();
svg = d3.select("#chart svg")
.call(d3.behavior.zoom()
.on("zoom", redraw))
.append("g");
var bg = svg.append("g")
.attr("id", "background");
/* Background must in fact be in front of user layer */
svg.insert("g", "#background")
.attr("id", "user_layer");
loadCacheJson("data/geofla/departement.json", function(json) {
bg.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("d", path);
});
d3.select("#compute").on("click", recomputeValues);
d3.select("#mapfiles").on("change", changeMap);
d3.select("#palette").on("change", updatePalette);
d3.selectAll("#buckets, input[name=scale]")
.on("change", recomputeScale);
changeMap();
loadCSV("data/csv/participation_pres.csv", function (r) {
return {
departement: r.departement,
data: [["participation_pres_" + r.date, parseFloat(r.participation)]]
};
});
loadCSV("data/csv/pres_2012_dpt_T1.csv", function(r) {
return {
departement: pad(r["Code du département"], 2),
data: extractData(r, parseInt, [
["Inscrits","pres_2012_T1_Inscrits"],
["Abstentions","pres_2012_T1_Abstentions"],
["Votants","pres_2012_T1_Votants"],
["Blancs et nuls","pres_2012_T1_Blancs-nuls"],
["Exprimés","pres_2012_T1_Exprimés"],
["JOLY","pres_2012_T1_JOLY"],
["LE PEN","pres_2012_T1_LE PEN"],
["SARKOZY","pres_2012_T1_SARKOZY"],
["MÉLENCHON","pres_2012_T1_MÉLENCHON"],
["POUTOU","pres_2012_T1_POUTOU"],
["ARTHAUD","pres_2012_T1_ARTHAUD"],
["CHEMINADE","pres_2012_T1_CHEMINADE"],
["BAYROU","pres_2012_T1_BAYROU"],
["DUPONT-AIGNAN","pres_2012_T1_DUPONT-AIGNAN"],
["HOLLANDE","pres_2012_T1_HOLLANDE"]
])
};
});
loadCSV("data/csv/pres_2012_dpt_T2.csv", function(r) {
return {
departement: pad(r["Code du département"], 2),
data: extractData(r, parseInt, [
["Inscrits","pres_2012_T2_Inscrits"],
["Abstentions","pres_2012_T2_Abstentions"],
["Votants","pres_2012_T2_Votants"],
["Blancs et nuls","pres_2012_T2_Blancs-nuls"],
["Exprimés","pres_2012_T2_Exprimés"],
["SARKOZY","pres_2012_T2_SARKOZY"],
["HOLLANDE","pres_2012_T2_HOLLANDE"]
])
};
});
loadCSV("data/csv/pres_2012_cant_T1.csv", function(r) {
return {
departement: pad(r["Code du département"], 2),
canton: pad(r["Code du canton"], 2),
data: extractData(r, parseInt, [
["Inscrits","pres_2012_T1_Inscrits"],
["Abstentions","pres_2012_T1_Abstentions"],
["Votants","pres_2012_T1_Votants"],
["Blancs et nuls","pres_2012_T1_Blancs-nuls"],
["Exprimés","pres_2012_T1_Exprimés"],
["JOLY","pres_2012_T1_JOLY"],
["LE PEN","pres_2012_T1_LE PEN"],
["SARKOZY","pres_2012_T1_SARKOZY"],
["MÉLENCHON","pres_2012_T1_MÉLENCHON"],
["POUTOU","pres_2012_T1_POUTOU"],
["ARTHAUD","pres_2012_T1_ARTHAUD"],
["CHEMINADE","pres_2012_T1_CHEMINADE"],
["BAYROU","pres_2012_T1_BAYROU"],
["DUPONT-AIGNAN","pres_2012_T1_DUPONT-AIGNAN"],
["HOLLANDE","pres_2012_T1_HOLLANDE"]
])
};
});
loadCSV("data/csv/pres_2012_cant_T2.csv", function(r) {
return {
departement: pad(r["Code du département"], 2),
canton: pad(r["Code du canton"], 2),
data: extractData(r, parseInt, [
["Inscrits","pres_2012_T2_Inscrits"],
["Abstentions","pres_2012_T2_Abstentions"],
["Votants","pres_2012_T2_Votants"],
["Blancs et nuls","pres_2012_T2_Blancs-nuls"],
["Exprimés","pres_2012_T2_Exprimés"],
["SARKOZY","pres_2012_T2_SARKOZY"],
["HOLLANDE","pres_2012_T2_HOLLANDE"]
])
};
});
loadCSV("data/csv/pres_2012_com_T1.csv", function(r) {
return {
departement: pad(r["Code du département"], 2),
commune: pad(r["Code de la commune"], 3),
data: extractData(r, parseInt, [
["Inscrits","pres_2012_T1_Inscrits"],
["Abstentions","pres_2012_T1_Abstentions"],
["Votants","pres_2012_T1_Votants"],
["Blancs et nuls","pres_2012_T1_Blancs-nuls"],
["Exprimés","pres_2012_T1_Exprimés"],
["JOLY","pres_2012_T1_JOLY"],
["LE PEN","pres_2012_T1_LE PEN"],
["SARKOZY","pres_2012_T1_SARKOZY"],
["MÉLENCHON","pres_2012_T1_MÉLENCHON"],
["POUTOU","pres_2012_T1_POUTOU"],
["ARTHAUD","pres_2012_T1_ARTHAUD"],
["CHEMINADE","pres_2012_T1_CHEMINADE"],
["BAYROU","pres_2012_T1_BAYROU"],
["DUPONT-AIGNAN","pres_2012_T1_DUPONT-AIGNAN"],
["HOLLANDE","pres_2012_T1_HOLLANDE"]
])
};
});
loadCSV("data/csv/pres_2012_com_T2.csv", function(r) {
return {
departement: pad(r["Code du département"], 2),
commune: pad(r["Code de la commune"], 3),
data: extractData(r, parseInt, [
["Inscrits","pres_2012_T2_Inscrits"],
["Abstentions","pres_2012_T2_Abstentions"],
["Votants","pres_2012_T2_Votants"],
["Blancs et nuls","pres_2012_T2_Blancs-nuls"],
["Exprimés","pres_2012_T2_Exprimés"],
["SARKOZY","pres_2012_T2_SARKOZY"],
["HOLLANDE","pres_2012_T2_HOLLANDE"]
])
};
});
}
function pad(s, n) {
while(s.length < n)
s = "0".concat(s);
return s;
}
function extractData(row, parse, fields) {
var data = [];
for (k in fields) {
data.push([fields[k][1], parse(row[fields[k][0]])]);
}
return data;
}
function updateRows() {
for (k in data) {
var id = "#data-" + k;
var li = d3.select(id).selectAll("li")
.data(data[k].properties.asArray().sort(),
function(d) { return d; });
li.enter().append("li")
.text(function(d){ return d;});
li.exit().remove();
;
}
}
function loadCSV(file, parse) {
/* parse must return an object with the following attributes:
* - data: an array of [ key, value ] arrays
* - for a departement: departement
* - for an arrondissement: departement and arrondissement
* - for a canton: departement and canton
* - for a commune: either departement and commune, or insee.
*/
d3.csv(file, function(rows) {
rows.forEach(function(r) {
var o = parse(r);
var dict, index, i;
if(typeof o.insee != "undefined") {
dict = data.commune;
index = o.insee;
} else if(typeof o.departement == "undefined") {
return;
} else if(typeof o.arrondissement != "undefined") {
dict = data.arrondissement;
index = o.departement.concat(o.arrondissement);
} else if(typeof o.canton != "undefined") {
dict = data.canton;
index = o.departement.concat(o.canton);
} else if(typeof o.commune != "undefined") {
dict = data.commune;
index = o.departement.concat(o.commune);
} else {
dict = data.departement;
index = o.departement;
}
if(typeof dict[index] == "undefined") {
dict[index] = {};
}
for (i in o.data) {
dict[index][o.data[i][0]] = o.data[i][1];
dict.properties.add(o.data[i][0]);
}
});
recomputeValues();
updateRows();
});
}
function buildScale(domain, buckets, scaleType) {
var legendClass = function(n) { return "q"+n+"-"+buckets; };
var minmax = d3.extent(domain);
var min = minmax[0]; var max = minmax[1];
if(scaleType == "symmetry") {
if(min < 0 && max < 0)
max = 0;
else if (min < 0 && max > 0) {
min = - Math.max(-min, max);
max = - min;
} else
min = 0;
}
var a = d3.range(buckets).map(legendClass);
var scale, q;
if(scaleType == "quantile") {
scale = d3.scale.quantile().range(a).domain(domain);
q = d3.merge([[min], scale.quantiles(), [max]]);
} else { /* quantize or symmetry */
scale = d3.scale.quantize().range(a).domain([min, max]);
q = d3.range(buckets + 1).map(function(n) {
return min + (max - min) * (n/buckets);
});
}
q = q.map(function(n) { return n.toPrecision(3); });
var leg = d3.select("#legend").selectAll("div")
.data(d3.range(buckets));
/* Enter */
var div = leg.enter().append("div");
div.append("svg").append("rect")
.attr("width", "100%").attr("height", "100%");
div.append("span");
/* Update */
leg.attr("class", legendClass);
leg.select("span").text(function(d,i){
return "[ "+q[i]+" ; "+ q[i+1] + " ]";
});
/* Exit */
leg.exit().remove();
return scale;
}
function updatePalette() {
var select, palette;
select = d3.select("#palette").node();
palette = select.options[select.selectedIndex].value;
svg.select("#user_layer").attr("class", palette);
d3.select("#legend").attr("class", palette);
}
function recomputeScale() {
var p = d3.selectAll("#user_layer path");
var values = p.data().map(function(d) { return d.value; });
var scaleType =
d3.selectAll("input[name=scale]")
.filter(function() { return this.checked; }).node().value;
var select = d3.select("#buckets").node();
var buckets = parseInt(select.options[select.selectedIndex].value);
var scale = buildScale(values, buckets, scaleType);
p.attr("class", function(d) { return scale(d.value); });
}
function recomputeValues() {
d3.select("#compute").attr("disabled", "disabled");
var prog = d3.select("#fillcode").node().value;
var f = eval('(function() {' + prog + '})();');
d3.selectAll("#user_layer path")
.datum(function(d){
d.value = 0. + f(
function(key) {
var dpt = data.departement[d.properties.CODE_DEPT],
arr = data.arrondissement[d.properties.CODE_DEPT + d.properties.CODE_ARR],
cant = data.canton[d.properties.CODE_DEPT + d.properties.CODE_CANT],
com = data.commune[d.properties.INSEE_COM];
if(typeof com != "undefined" && typeof com[key] != "undefined")
return com[key];
if(typeof cant != "undefined" && typeof cant[key] != "undefined")
return cant[key];
if(typeof arr != "undefined" && typeof arr[key] != "undefined")
return arr[key];
if(typeof dpt != "undefined" && typeof dpt[key] != "undefined")
return dpt[key];
return undefined;
},
d.properties
);
return d; });
recomputeScale();
d3.select("#compute").attr("disabled", null);
}
function changeMap() {
var select = d3.select("#mapfiles").attr("disabled", "disabled").node();
var name = select.options[select.selectedIndex].value;
var mapfile = "data/geofla/" + name + ".json";
var oldLayer = svg.select("#user_layer")
.attr("id", "#old_layer");
var newLayer = svg.insert("g", "#background")
.attr("id", "user_layer");
updatePalette();
loadCacheJson(mapfile, function(json) {
newLayer.selectAll("path")
.data(json.features)
.enter().append("path")
.attr("d", path);
recomputeValues();
oldLayer.remove();
d3.select("#mapfiles").attr("disabled", null);
});
}
function redraw() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
addLoadEvent(init);
})();