forked from eraiyer/cases_deaths_hosps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
677 lines (589 loc) · 20.9 KB
/
index.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
// Created by Era Iyer
// May 2020
// index.js file
// generates state line chart graph using d3 library
// resources: https://bl.ocks.org/officeofjane/2c3ed88c4be050d92765de912d71b7c4 for US grid
var csv_arr = []; //global array to hold certain state and color values from csv file
fillArr(); //populates csv array [{state, color},{state, color}, {state, color},...]
//var selectOptions = ["Daily New Cases", "Daily New Deaths", "Current Hospitalizations"]
var selectOptions = ["Daily New Cases", "Daily New Deaths"]
// add the options to the button
d3.select("#selectButton")
.selectAll('myOptions')
.data(selectOptions)
.enter()
.append('option')
.text(function (d) { return d; }) // text showed in the menu
.attr("value", function (d) { return d; }) // corresponding value returned by the button
var margin = {top:20, right:20, bottom:20, left:20},
width = window.innerWidth - margin.left - margin.right,
height = window.innerHeight - margin.top - margin.bottom;
// calculate cellSize based on dimensions of svg
var cols = 13;
var rows = 8;
var cellSize = calcCellSize(width, height, cols, rows);
// generate grid data with specified number of columns and rows
var gridData = gridData(13, 8, cellSize);
var g_svg = d3.select("#graphModal")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
indexSelected();
d3.select("#vis")
.attr("align","center");
/*
* indexSelected: determines index selected from dropdown, calls function to create US map grid,
* and preloads json data for efficiency
*/
function indexSelected() {
margin = {top:20, right:20, bottom:20, left:20};
var x = document.getElementById("selectButton").selectedIndex;
var y = document.getElementById("selectButton").options;
d3.selectAll("#vis > *").remove();
svg = d3.select("#vis")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
grid = svg.append("g")
.attr("class", "gridlines")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var row = grid.selectAll(".row")
.data(gridData)
.enter()
.append("g")
.attr("class", "row");
column = row.selectAll(".cell")
.data(function(d) { return d; })
.enter()
.append("rect")
.attr("class", "cell")
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.attr("width", function(d) { return d.width; })
.attr("height", function(d) { return d.height; })
.style("fill", "white");
gridMap = svg.append("g")
.attr("class", "gridmap")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// preloading csv files and json data as parameters for the function 'ready'
setTimeout(function() {
// load json data and trigger callback
d3.json("./result.json", function(data) {
// instantiate chart within callback
d3.queue()
.defer(d3.csv, "publication-grids.csv")
.defer(d3.csv, "links.csv")
.defer(setData, data)
.defer(selectIndex)
.await(ready);
});
}, 1500);
function setData(data, callback){
callback(null, data)
}
function selectIndex(callback) {
index = y[x].value;
if (index == null){
index = 1
}
callback(null, index);
}
}
/*
* ready: graws grid, labels, and calls function to populate grid boxes
*/
function ready(error, data, links, jsonData, selectedIndex) {
var nest = d3.nest()
.key(function(d) { return d.publication; })
.entries(data);
// drawing grid map
drawGridMap(links[0].publication);
// function to create initial map
function drawGridMap(publication) {
// filter data to return the object of publication of interest
var selectPub = nest.find(function(d) {
return d.key == publication;
});
// use a key function to bind rects to states
var states = gridMap.selectAll(".state")
.data(selectPub.values, function(d) {return d.code; });
// draw state rects
states.enter()
.append("rect")
.attr("class", function(d) {
return "state " + d.code;
})
.attr("x", function(d) { return (d.col-1) * cellSize; })
.attr("y", function(d) { return (d.row - 1) * cellSize; })
.attr("width", cellSize)
.attr("height", cellSize)
.on("click", function(d) {
var square = d3.select(this);
square.classed("active", !square.classed("active"));
if (square.classed("active")) {
let color = getColor(d.state); //determines appropriate color based on id
popUpGraph(d.state, color, selectedIndex, jsonData);
}
});
var labels = gridMap.selectAll(".label")
.data(selectPub.values, function(d) { return d.code; });
// add state labels
labels.enter()
.append("text")
.attr("class", function(d) { return "label " + d.code; })
.attr("x", function(d) {
return ((d.col - 1) * cellSize);
})
.attr("y", function(d) {
return ((d.row - 1) * cellSize) + (cellSize*0.3);
})
.style("text-anchor", "start")
.text(function(d) {
return d.code;
});
var map = gridMap.selectAll(".map")
.data(selectPub.values, function(d) { return d.code; });
// graphs for each state
map.enter()
.append("svg")
.attr("stateMap", function(d) {
var color = getColor(d.state); //determines appropriate color based on preloaded csv file
x = ((d.col - 1) * cellSize);
y = ((d.row - 1) * cellSize);
populate(x, y, d.state, color, selectedIndex, jsonData);
})
}
};
/*
* getColor: determines corresponding color based on the id given. If there is a change
* in color, it returns the changed color, else returns the old color
*/
function getColor(state){
for(var i = 0; i < csv_arr.length; i ++){
if(csv_arr[i][0] == state){ //find correct province/state
return csv_arr[i][1]; //return color
}
}
}
/*
* popUpGraph: takes in stateName and generates Modal with graph of
* the state selected
*/
function popUpGraph(stateName, color, selectedIndex, data) {
var modal = document.getElementById("myModal");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
//if 'x' button clicled, hide modal and reset g_svg
span.onclick = function() {
modal.style.display = "none";
d3.selectAll("#graphModal > *").remove();
g_svg = d3.select("#graphModal")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("align","center");
d3.selectAll("#graphTitle > *").remove();
}
//if non-modal section clicled, hide modal and reset g_svg
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
d3.selectAll("#graphModal > *").remove();
g_svg = d3.select("#graphModal")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("align","center");
d3.selectAll("#graphTitle > *").remove();
}
}
modal.style.display = "block";
//setting svg height, width, and margin values
var w = width * 0.8,
h = height *0.5,
padding = 45;
var file="./result.json";
const dataset = [];
var yAxisLabel;
var hoverOverText;
if(selectedIndex == 'Daily New Cases'){
//determine index from JSON corresponding to state name
var index = data.findIndex(obj => obj.state==stateName);
for(var i = 0; i < data[index].dates.length; i++){
//pushes date and value into array, similar to x, y coordinates on a graph
dataset.push({ x : d3.timeParse("%Y-%m-%d")(data[index].dates[i]), y : data[index].new_cases[i] });
}
yAxisLabel = 'Daily New Cases';
hoverOverText = ' new cases on ';
}
else if(selectedIndex == 'Daily New Deaths'){
//determine index from JSON corresponding to state name
var index = data.findIndex(obj => obj.state==stateName);
// state = data[selectedIndex].state;
for(var i = 0; i < data[index].dates.length; i++){
//pushes date and value into array, similar to x, y coordinates on a graph
dataset.push({ x : d3.timeParse("%Y-%m-%d")(data[index].dates[i]), y : data[index].new_deaths[i] });
}
yAxisLabel = 'Daily New Deaths';
hoverOverText = ' new deaths on ';
}
// else if(selectedIndex == 'Current Hospitalizations'){
// //determine index from JSON corresponding to state name
// var index = data.findIndex(obj => obj.state==stateName);
// for(var i = 0; i < data[index].hospDates.length; i++){
// //pushes date and value into array, similar to x, y coordinates on a graph
// dataset.push({ x : d3.timeParse("%Y-%m-%d")(data[index].hospDates[i]), y : data[index].new_hospitalizations[i] });
// }
// yAxisLabel = 'Patients Hospitalized';
// hoverOverText = ' patients in the hospital on ';
// }
var x = d3.scaleTime().range([padding, w - padding]);
var y = d3.scaleLinear().range([h, padding*0.2]);
var xAxis = d3.axisBottom()
.scale(x)
.ticks(d3.timeMonth);
var yAxis = d3.axisLeft()
.scale(y)
.ticks(5);
x.domain(d3.extent(dataset, function(d) { return d.x; }));
y.domain([0, d3.max(dataset, function(d) { return d.y; })]);
g_svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate("+padding*0.5+"," + h + ")")
.call(xAxis.ticks(6).tickSize(0));
// .call(xAxis);
g_svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate("+padding*1.5+",0)")
.call(yAxis.ticks(null).tickSize(0));
//.call(yAxis);
// const line = d3.line()
// .x(function(d) { return xAxis(d.x) })
// .y(function(d) { return yAxis(d.y) })
g_svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", padding*0.25)
.attr("x",0 - (h / 2))
.attr("dy", "1em")
.style("font-size", function(d){
if(width < 300 || height < 400){ return "10px"; }
else{ return "14px"; }
})
.style("text-anchor", "middle")
.text(yAxisLabel);
d3.select("#graphTitle").append("text")
.attr("transform", "translate(" + (w/2) + " ," +
(20) + ")")
.style("text-anchor", "middle")
.text(stateName)
.style("font-size", function(d){
if(width < 300 || height < 400){ return "16px"; }
else{ return "24px"; }
});
var div = d3.select("#graphInfo").append("div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("background-color", "white")
.style("border", "dotted")
.style("border-width", "1px")
.style("border-radius", "3px")
.style("opacity", 0);
g_svg.selectAll(".bar")
.data(dataset)
.enter().append("rect")
.attr("class", "bar")
.attr("fill", color)
.attr("opacity", "0.3")
.attr("transform", "translate("+padding*0.5+",0)")
.attr("x", function(d) { return x(d.x); })
.attr("width", w/dataset.length)
.attr("y", function(d) { return y(d.y); })
.attr("height", function(d) { return h - y(d.y); })
.on('mouseover', function (d, i) {
d3.select(this).transition()
.duration('100')
.attr("opacity", "0.7")
div.transition()
.duration(100)
.style("opacity", 1);
div.html((Math.round(d.y))+ hoverOverText + d3.timeFormat("%B %d")(d.x))
.style("font-size", "12px")
// .style("left",(d3.mouse(this)[0]+90) + "px")
// .style("top", (d3.mouse(this)[1]) + "px")
.style("left",(d3.event.pageX) + "px")
.style("top", (d3.event.pageY) + "px")
.style("padding", "3px")
.style("padding-bottom", "15px");
})
.on('mouseout', function (d, i) {
d3.select(this).transition()
.duration('200')
.attr("opacity", "0.3");
div.transition()
.duration('200')
.style("opacity",0)
});
// g_svg.append("path")
// .datum(dataset)
// .attr("fill", "none")
// .attr("transform", "translate("+padding*0.5+",0)")
// .attr("stroke", color)
// .attr("stroke-width", 1)
// .attr("d", line);
//opening json file to read data only from the selected index
// setting time scale for x axis based on dates
/*var xScale = d3.scaleTime()
.domain(d3.extent(dataset, function(d) { return d.x; }))
.range([padding, w - padding]); //taking into account margins
// setting linear scale for y axis based on max value
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function (d) { return d.y; })])
.range([h, padding*0.2]);
var xAxis = d3.axisBottom(xScale).ticks(d3.timeMonth);
var yAxis = d3.axisLeft(yScale).ticks(5);
//draw x axis in modal
g_svg.append("g")
.attr("transform", "translate("+padding*0.5+"," + (h) + ")")
.call(xAxis)
.selectAll("text")
.attr("dy", ".25em")
.attr("dx", "-.8em")
.attr("transform", "rotate(-45)")
.style("text-anchor", "end");
//draw y axis in modal
g_svg.append("g")
.attr("transform", "translate("+padding*1.5+",0)")
.call(yAxis);
g_svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", padding*0.25)
.attr("x",0 - (h / 2))
.attr("dy", "1em")
.style("font-size", function(d){
if(width < 300 || height < 400){ return "10px"; }
else{ return "14px"; }
})
.style("text-anchor", "middle")
.text(yAxisLabel);
d3.select("#graphTitle").append("text")
.attr("transform", "translate(" + (w/2) + " ," +
(20) + ")")
.style("text-anchor", "middle")
.text(stateName)
.style("font-size", function(d){
if(width < 300 || height < 400){ return "16px"; }
else{ return "24px"; }
});
// //add title to graph
// g_svg.append("text")
// .attr("transform",
// "translate(" + (w/2) + " ," +
// (10) + ")")
// .style("text-anchor", "middle")
// .text(stateName)
// //.style("font-size", "24px")
// .style("font-size", function(d){
// if(width < 300 || height < 400){
// return "16px";
// }
// else{
// return "24px";
// }
// })
// .style("fill", "#696969");
//draw line and path
const line = d3.line()
.x(function(d) { return xScale(d.x) })
.y(function(d) { return yScale(d.y) })
g_svg.append("path")
.datum(dataset)
.attr("fill", "none")
.attr("transform", "translate("+padding*0.5+",0)")
.attr("stroke", color)
.attr("stroke-width", 1)
.attr("d", line)
const area = d3.area()
.x(function(d) { return xScale(d.x); })
.y0(h)
.y1(function(d) { return yScale(d.y); });
g_svg.append("path")
.datum(dataset)
.attr("class", "area")
.attr("transform", "translate("+padding*0.5+",0)")
.attr("fill", color)
.attr("opacity", "0.2")
.attr("cursor", "pointer")
.attr("d", area);
var div = d3.select("#graphInfo").append("div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("background-color", "white")
.style("border", "dotted")
.style("border-width", "1px")
.style("border-radius", "3px")
.style("opacity", 0);
//place dots to represent all x y coordinates
g_svg
.append("g")
.selectAll("dot")
.data(dataset)
.enter()
.append("circle")
.attr("cx", function(d) { return xScale(d.x) } )
.attr("cy", function(d) { return yScale(d.y) } )
.attr("r", 2)
.attr("fill", color)
.attr("transform", "translate("+padding*0.5+",0)")
//interactive feature to see new cases/deaths/hosps per day
.on('mouseover', function (d, i) {
d3.select(this).transition()
.duration('100')
.attr("r", 7);
div.transition()
.duration(100)
.style("opacity", 1);
div.html((Math.round(d.y))+ hoverOverText + d3.timeFormat("%B %d")(d.x))
.style("font-size", "12px")
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY) + "px")
.style("padding", "3px")
.style("padding-bottom", "15px");
})
.on('mouseout', function (d, i) {
d3.select(this).transition()
.duration('200')
.attr("r", 2);
div.transition()
.duration('200')
.style("opacity", 0);
});*/
}
/*
* fillArr: reads csv file and populates csv_arr with all id, change, and old color values.
* *This process of preloading is to get around the asynchronous javascript process*
*/
function fillArr(){
d3.csv("USStateColors.csv", function(data) {
for(var i = 0; i < data.length; i++){
csv_arr.push([data[i].state, data[i].color]);
}
});
}
/*
* gridData: function that generates a nested array for square grid
*/
function gridData(ncol, nrow, cellsize) {
var gridData = [];
var xpos = 1; // starting xpos and ypos at 1 so the stroke will show when we make the grid below
var ypos = 1;
// calculate width and height of the cell based on width and height of the canvas
var cellSize = cellsize;
// iterate for rows
for (var row = 0; row < nrow; row++) {
gridData.push([]);
// iterate for cells/columns inside each row
for (var col = 0; col < ncol; col++) {
gridData[row].push({
x: xpos,
y: ypos,
width: cellSize,
height: cellSize
});
// increment x position (moving over by 50)
xpos += cellSize;
}
// reset x position after a row is complete
xpos = 1;
// increment y position (moving down by 50)
ypos += cellSize;
}
return gridData;
}
/*
* gridData: function to calculate grid cell size based on width and height of svg
*/
function calcCellSize(w, h, ncol, nrow) {
// leave tiny space in margins
var gridWidth = w-2;
var gridHeight = h -2;
var cellSize;
// calculate size of cells in columns across
var colWidth = Math.floor(gridWidth / ncol);
// calculate size of cells in rows down
var rowWidth = Math.floor(gridHeight / nrow);
// take the smaller of the calculated cell sizes
if (colWidth <= rowWidth) {
cellSize = colWidth;
} else {
cellSize = rowWidth;
}
return cellSize;
}
/*
* populate: generates graph for state given and translates axes and coordinates
* based on x y position
*/
function populate(x, y, state, color, selectedIndex, data){
const dataset = [];
if(selectedIndex == 'Daily New Cases'){
//determine index from JSON corresponding to state name
var index = data.findIndex(obj => obj.state==state);
for(var i = 0; i < data[index].dates.length; i++){
//pushes date and value into array, similar to x, y coordinates on a graph
dataset.push({ x : d3.timeParse("%Y-%m-%d")(data[index].dates[i]), y : data[index].avg_cases[i] });
}
}
else if(selectedIndex == 'Daily New Deaths'){
//determine index from JSON corresponding to state name
var index = data.findIndex(obj => obj.state==state);
for(var i = 0; i < data[index].dates.length; i++){
//pushes date and value into array, similar to x, y coordinates on a graph
dataset.push({ x : d3.timeParse("%Y-%m-%d")(data[index].dates[i]), y : data[index].avg_deaths[i] });
}
}
// else if(selectedIndex == 'Current Hospitalizations'){
// var index = data.findIndex(obj => obj.state==state);
// for(var i = 0; i < data[index].hospDates.length; i++){
// //pushes date and value into array, similar to x, y coordinates on a graph
// dataset.push({ x : d3.timeParse("%Y-%m-%d")(data[index].hospDates[i]), y : data[index].avg_hospitalizations[i] });
// }
// }
var w = cellSize*.85,
h = cellSize*.85;
margin = { top: 10, right: 10, bottom: 0, left: 10 };
// setting time scale for x axis based on date
var xScale = d3.scaleTime()
.domain(d3.extent(dataset, function(d) { return d.x; }))
.range([0,w]); //taking into account margins
// setting linear scale for y axis based on max value
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function (d) { return d.y + 1; })])
.range([h, margin.top]);
var xAxis = d3.axisBottom(xScale).tickValues([]).tickSizeOuter(0);
var yAxis = d3.axisLeft(yScale).tickValues([]);
const line = d3.line()
.x(function(d) { return xScale(d.x) })
.y(function(d) { return yScale(d.y) })
d3.select("svg").append("path")
.datum(dataset)
.attr("fill", "none")
.attr("stroke", color)
.attr("stroke-width", 1)
.attr("transform", "translate(" + [x+margin.left*2,y+margin.top*2] + ")") //translate line based on x and y position
.attr("d", line)
const area = d3.area()
.x(function(d) { return xScale(d.x); })
.y0(h)
.y1(function(d) { return yScale(d.y); });
d3.select("svg").append("path")
.datum(dataset)
.attr("class", "area")
.attr("transform", "translate(" + [x+margin.left*2,y+margin.top*2] + ")")
.attr("fill", color)
.attr("opacity", "0.2")
.attr("cursor", "pointer")
.on("click", function(d) {
popUpGraph(state, color, selectedIndex, data);
})
.attr("d", area);
}