-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchoroplethExample.html
392 lines (298 loc) · 16.7 KB
/
choroplethExample.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
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
<html><head>
<title>INFO 3300 - October 13</title>
<link href="https://fonts.googleapis.com/css?family=Lato:400,700|Raleway:400,700" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../css/normalize.css">
<link rel="stylesheet" type="text/css" href="../css/skeleton.css">
<link rel="stylesheet" type="text/css" href="../css/custom-style.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/styles/default.min.css">
<link rel="stylesheet" href="../css/hljs-base16.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/highlight.min.js"></script>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://d3js.org/topojson.v3.min.js"></script>
<style>
.state {
fill: lightgrey;
}
.outline {
stroke: black;
stroke-width: 1px;
fill: none;
}
.graticule {
fill: none;
stroke: grey;
stroke-width: 1px;
}
</style>
</head>
<body>
<div class="container larger">
<h3>Notes for October 13</h3>
<input id = 'input-field'></input>
<svg id="choropleth" height="600" width="900" style="background: #445; margin-top:50px" >
</svg>
<svg id="colorLegend" height="100" width="600" style="background: #fff; margin-top:30px" >
</svg>
<!-- This block will be automatically filled with syntax-highlighted code from the script below -->
<h5>Code for today:</h5>
<pre>
<code id="display1" class="hljs javascript">
</code>
</pre>
<!--- Code for today's class --->
<script id="notes1">
const svg = d3.select("#choropleth");
const width = svg.attr("width");
const height = svg.attr("height");
const margin = { top: 20, right: 20, bottom: 20, left:20};
const mapWidth = width - margin.left - margin.right;
const mapHeight = height - margin.top - margin.bottom;
const map = svg.append("g")
.attr("transform","translate("+margin.left+","+margin.top+")");
// 0. Let's explore a new way to use promises for data imports that might be a bit cleaner when importing lots of files
// First, create an anonymous function with the async keyword and assign it to a variable
// This creates a function that returns a promise (meaning it is run `asynchronously`)
// Try leaving out the async -- you'll see the change in what line 81 prints
const testFunc = async function() {
return "Hello" ;
}
//console.log( testFunc() );
// We use async functions because they give access to *await* which can make code a lot easier to read
// See docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
// * Start by making an anonymous async function which will contain most or all of your code *
// * Make sure to run the function after you make it (see bottom of file) *
// *** If it seems like nothing is happening, make sure you are running it ***
// * Then use await instead of .then() -- see line 98
// 1. An async function to load data and build the map
const requestData = async function() {
// 2. Draw a map of US using topoJSON
// 2a. Import data as synchronous call to topoJSON data file
// Care of Mike Bostock:
// "../datasets/us-smaller.json"
const us = await d3.json("us-smaller.json");
console.log(us);
// 2b. Pick out topographic features and build d3 helpers
var states = topojson.feature(us, us.objects.states); // List of state outlines to fill
var statesMesh = topojson.mesh(us, us.objects.states); // 'Mesh' of all outlines put together for a stroke
var projection = d3.geoAlbersUsa().fitSize([mapWidth, mapHeight], states);
var path = d3.geoPath().projection(projection);
console.log(states);
console.log(statesMesh);
// We tried a few different projections, including:
// .geoOrthographic().rotate([90,-30,0]) .geoConicEqualArea() .geoMercator()
// 2d. Add a graticule (we did this after 2c, but it must go here)
// (Graticules are much more configurable, but we'll use the default for now)
var graticule = d3.geoGraticule10();
map.append("path").attr("class","graticule").attr("d", path(graticule) )
// 2c. Draw states and outlines (see CSS at the top)
map.selectAll("path.state").data(states.features)
.join("path")
.attr("class", "state")
.attr("note", d => d.id) // debugging
.attr("d", path)
.on('mouseover', mouseEntersPlot )
.on('mouseout', mouseLeavesPlot );
map.append("path").datum(statesMesh)
.attr("class","outline")
.attr("d", path);
// 3a. Import survey data as synchronous calls
// "../datasets/state-survey-responses-fa21.csv"
var surveyData = await d3.csv("state-survey-responses-fa21.csv", d3.autotype);
console.log(surveyData)
let choroplethData = await d3.json('example.json', d3.autotype);
console.log("CHOROPLETH DATA");
console.log(choroplethData);
// Get the username from the field
let inputFieldValue = d3.select('.input-field').value
console.log(inputFieldValue);
console.log("NEW USER");
let username = 'RealSkipBayless';
surveyData.forEach( obj => {
obj.total = choroplethData[obj.state_name][username];
})
console.log('NEW DATA');
console.log(surveyData);
// 3b. Generate the dictionary we will need
let stateIdCounts = {}; // stateIdCounts[ stateId ] -> count
let stateIdNames = {}; // stateIdNames[ stateId ] -> name
surveyData.forEach( row => {
stateIdCounts[ row.state_code ] = Number(row.total);
stateIdNames[ row.state_code ] = row.state_name;
});
console.log(stateIdCounts)
// 3c. Make a d3 color scale for frequency
// Notice that stateIdCounts is a dictionary and not an array, which is usually what we send to d3.extent
// We're only interested in the values in that dictionary, so we can use a static helper function in Object to help
const minMax = d3.extent( Object.values(stateIdCounts) );
console.log(minMax);
// This scale wasn't great because it crunched most of the points to the bottom 3rd of the color scale
// 3 state outliers with high values mean it is very distorted
// const colorScale = d3.scaleSequential(d3.interpolateGnBu).domain(minMax);
// Next, we try quantize, which splits the domain into bins
// In general, it splits it into as many bins as you provide items in the range
// const colorScale = d3.scaleQuantize()
// .domain(minMax)
// .range(["rgb(233, 240, 194)", "rgb(174, 226, 142)", "rgb(45, 177, 149)", "rgb(36, 112, 191)"])
// NOTE: I tried to make the scale a little bit less ugly than the one I demoed in class -- with varying degrees of success...
// Finally, we use quantile, which looks at the points statistically
// It will give weird results if you send minMax to the .domain(). Why?
// ...because it needs to inspect *all of the values* in order to see the point *distribution*
// we use Object.values() here to get all of the values out of the stateCounts dictionary
const colorScale = d3.scaleQuantile()
.domain(Object.values(stateIdCounts))
.range(["#fff","#d1e8ed","#adc2da","#8879b3","#762b80"]);
// // If you want to use a log scale instead of a linear quantile (which might work better):
// // Here is one way to do this (note the use of Symlog because our domain includes 0)
// // We create a new function that feeds the data value into a Symlog scale programmed to return 0 to 1
// // It then routes the [0,1] value to interpolateGnBu, which returns a color, doing what we want
// // Just like with normal scales, you feed them a data value and get back a color/pixel
// const colorScale = d => d3.interpolateGnBu( d3.scaleSymlog().domain(minMax).range([0,1])(d) );
// colorScale.domain = () => minMax; // Hack to get legend working again because it uses scale.domain()
// // Another way to do this would be:
// const colorScale = d3.scaleLog().domain(minMax).interpolate(d => d3.interpolateGnBu)
// // Getting a scaleQuantile to work would be a bit trickier
// // You'll want to think about how to adjust the domain of the scale (hint: d3.map to transform data)
// // and then also how you're going to show the values legend in the bottom scale
// 3d. Recolor the states to make a choropleth map
map.selectAll(".state")
.style("fill", d => colorScale( stateIdCounts[d.id]) );
// 3e. Use the extra legend code to draw a legend
drawLegend(d3.select("#colorLegend"), colorScale);
// 4. Add a tooltip that "sticks" below the state
let tooltipWidth = 120;
let tooltipHeight = 40;
// At the end of lecture segment, we added this code to do the mouseover outline the "proper" way
let momesh = map.append("path")
.attr("class","mouseover outline")
.attr("d", "");
// Stub code to draw the tooltip - we use an SVG element here
// You can use an absolute-positioned HTML element, but the positioning requires some more work
// Instead, we make something centered at (0,0) and then later use translate() to move it
// (this is why the x position for the rect is -tooltipWidth/2.0 -- so it's centered on 0 )
let tooltip = map.append("g")
.attr("class","tooltip")
.attr("visibility","hidden");
tooltip.append("rect")
.attr("fill", "black")
.attr("opacity", 0.9)
.attr("x", -tooltipWidth / 2.0)
.attr("y", 0)
.attr("width",tooltipWidth)
.attr("height",tooltipHeight)
let txt = tooltip.append("text")
.attr("fill", "white")
.attr("text-anchor","middle")
.attr("alignment-baseline","hanging")
.attr("x", 0)
.attr("y", 2);
let txt2 = tooltip.append("text")
.attr("fill", "white")
.attr("text-anchor","middle")
.attr("alignment-baseline","hanging")
.attr("x", 0)
.attr("y", 22);
d3.selectAll(".state").on("mouseenter", mouseEntersPlot);
d3.selectAll(".state").on("mouseout", mouseLeavesPlot);
function mouseEntersPlot() {
// Make tooltip visible
tooltip.style("visibility","visible")
// Find the state SVG element and add stroke
let state = d3.select(this);
// // Original version
// state.attr("stroke","black")
// .attr("stroke-width", 3);
// Using .datum() to recover the data for the state element (because we used a .join() to make it)...
// ... get the name of the state and count
let stateID = state.datum().id;
console.log(state.datum())
txt.text(stateIdNames[ stateID ]);
txt2.text(stateIdCounts[ stateID ]);
// You can use the geoPath() generator to do all sorts of helpful things
// let centroid = path.centroid( state.datum() ); // Get the pixel "center" of the state
let bounds = path.bounds( state.datum() ); // Get the pixel boundaries of the state
// In both cases here, the geoPath() is parsing the fancy topoJSON data to figure out pixels using the projection
// Place it at the bottom of the state, centered
let xPos = (bounds[0][0]+bounds[1][0])/2.0;
let yPos = bounds[1][1] - 15;
// Transform the <g> group so that everything moves together easily
tooltip.attr("transform",`translate(${xPos},${yPos})`);
// To fix the oscillation, we add this in the CSS for .mouseover
// pointer-events: none;
// Technically, the right way to do this is with another mesh for some complicated reasons
// You have to use the second parameter of topojson.mesh() to pick out this state's boundaries
// At the end of the lecture we tried this out
// First, make a new mesh with a filter for only borders of the current state
var mo = topojson.mesh(us, us.objects.states, function(a, b) { return a.id === stateID || b.id === stateID; });
// Then apply it to your special mesh that's on top of everything else
momesh.datum(mo).attr("d", path)
}
function mouseLeavesPlot() {
// Hide when you leave a state
tooltip.style("visibility","hidden");
let state = d3.select(this);
// Reset old style mouseover stroke
// state.attr("stroke","none")
// .attr("stroke-width", 0);
// }
// Here we are hiding the mouseover mesh we added at the end of the lecture
momesh.attr("d", "");
}
}
// END OF REQUESTDATA()
requestData();
</script>
<script>
// Function needs a d3 selected SVG canvas where it will draw the legend and a source color scale
function drawLegend(legend, legendColorScale) {
// Bonus code here to draw an adaptive gradient legend so we can see different color scales for choropleth maps
// Credit Prof. Rz if you are basing a legend on this structure, and note SERIOUS PERFORMANCE CONSIDERATIONS
//const legend = d3.select("#colorLegend");
const legendWidth = legend.attr("width");
const legendHeight = legend.attr("height");
const legendMinMax = d3.extent(legendColorScale.domain()); // way to recover the minMax from most kinds of scales
const barHeight = 60;
const stepSize = 4; // warning, not using a canvas element so lots of rect tags will be created for low stepSize, causing issues with performance
// Extend the minmax by 1 in either direction to expose more features
const pixelScale = d3.scaleLinear().domain([0,legendWidth-40]).range([legendMinMax[0]-1,legendMinMax[1]+1]); // In this case the "data" are pixels, and we get numbers to use in colorScale
const barScale = d3.scaleLinear().domain([legendMinMax[0]-1,legendMinMax[1]+1]).range([0,legendWidth-40]);
const barAxis = d3.axisBottom(barScale);
// Check if we're using a quantile scale - if so, we can do better
if (legendColorScale.hasOwnProperty('quantiles')) {
// Use the quantile breakpoints plus the min and max of the scale as tick values
barAxis.tickValues(legendColorScale.quantiles().concat( legendMinMax ));
}
legend.append("g")
.attr("class", "colorbar axis")
.attr("transform","translate("+(20)+","+(barHeight+5)+")")
.call(barAxis);
// Draw rects of color down the bar
let bar = legend.append("g").attr("transform","translate("+(20)+","+(0)+")")
for (let i=0; i<legendWidth-40; i=i+stepSize) {
bar.append("rect")
.attr("x", i)
.attr("y", 0)
.attr("width", stepSize)
.attr("height",barHeight)
.style("fill", legendColorScale( pixelScale(i) )); // pixels => countData => color
}
// Put lines in to mark actual min and max of our data
bar.append("line").attr("stroke","white").attr("stroke-width",3).attr("x1", barScale(legendMinMax[0])).attr("x2", barScale(legendMinMax[0])).attr("y1", 0).attr("y1", barHeight+4);
bar.append("line").attr("stroke","white").attr("stroke-width",3).attr("x1", barScale(legendMinMax[1])).attr("x2", barScale(legendMinMax[1])).attr("y1", 0).attr("y1", barHeight+4);
}
</script>
<!--- calls the highlight library to fill the <pre> tag with code --->
<script>
function sanitize(s) {
return s.replace("<br>", "\\n")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
document.getElementById("display1").innerHTML = sanitize( document.getElementById("notes1").innerText);
hljs.highlightAll();
</script>
</div>
</body>
</html>