-
Notifications
You must be signed in to change notification settings - Fork 2
/
scatter.html
1497 lines (1186 loc) · 40.3 KB
/
scatter.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
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>National Elections</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style type="text/css">
body {
color: #888;
font-family: serif;
font-size:15px;
}
svg {
/* margin-top: 2.5em;
margin-bottom: 2.5em;*/
}
.axis {
font: 12px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #aaa;
shape-rendering: crispEdges;
}
.axis text {
fill: #858585;
}
.title {
font: 500 100px serif;
fill: #e5e5e5;
}
.party {
font: 500 35px serif;
fill: #e5e5e5;
}
.incr {
font: 500 35px serif;
fill: #e5e5e5;
cursor: pointer;
}
.incr:hover {
fill: #ccc;
}
.circle {
stroke: white;
stroke-width: 0.2px;
/*https://stackoverflow.com/questions/5697067*/
cursor: pointer; /*grab; pointer; move; -webkit-grab;*/
fill-opacity: 0.9;
}
.circle:active {
/*Closed hand*/
/*https://stackoverflow.com/questions/5697067*/
cursor: grabbing;
cursor: -moz-grabbing;
cursor: -webkit-grabbing;
}
.circle:hover {
fill-opacity: 0.8;
}
#searchform {
padding-bottom: 5px;
}
#formholder {
position: absolute;
right: 50px;
top: 25px;
/*font: 16px serif;*/
}
.incrbtn {
font: 500 30px serif;
cursor: pointer;
background-color: Transparent;
background-repeat:no-repeat;
border: none;
cursor:pointer;
overflow: hidden;
/*outline:none;*/
color: #e5e5e5;
}
.incrbtn:hover {
color: #ccc;
}
#upclick {
position: absolute;
left: 55px;
bottom: 160px;
/*font: 16px serif;*/
}
#downclick {
position: absolute;
left: 55px;
bottom: 125px;
/*font: 16px serif;*/
}
#select {
padding:5px 0px;
}
input {
/*font: 14px serif;*/
}
</style>
</head>
<body>
<div id="formholder" >
<div id="select">
<select id="inds">
<option value="county" selected="selected">County</option>
<option value="state">State</option>
<option value="race">Race</option>
<option value="gender">Sex</option>
<option value="age">Age</option>
<option value="education">Education</option>
<!-- <input type="button" value="↻" onclick="reload();" > -->
</select>
</div>
<!-- onSubmit="return handleClick()" -->
<!-- <form id="searchform" name="myform"> -->
<span id="searchform" name="myform">
<input type="text" id="myVal" size="30" placeholder="NY, WI, Los Angeles County">
<input id="search" name="Submit" type="button" value="Search" onclick="handleClick();"> <!--onclick="handleClick();"-->
<input type="button" value="X" onclick="removeSearch();" > <!--document.myform.reset();-->
<!-- </form> -->
</span>
<form id="areaform">
Weight:
<input type="radio" name="area" value="vote" checked>Vote
<input type="radio" name="area" value="electoral" > Electoral
<input type="radio" name="area" value="vpi" >VPI<br>
</form>
</div>
<button class="incrbtn" id="upclick">▲</button>
<button class="incrbtn" id="downclick">▼</button>
<script type="text/javascript">
// {top: 20, right: 20, bottom: 50, left: 30}
var margin = {top: 30, right: 20, bottom: 50, left: 50},
width = 0.95*window.innerWidth - margin.left - margin.right,
height = 0.9*window.innerHeight - margin.top - margin.bottom;
//Globals:
var currentSearch = "";
var searchTerms = "";
var selection = "county";
var year;
var cache = {};
// var locurls = {
// 'county': './US_County_Level_Presidential_Results_04-16.csv',
// 'state': './US_State_Level_Presidential_Results_04-16.csv',
// 'demographic': './US_Demographic_Presidential_Results_04-16.csv'
// }
var locurls = {
'county': './US_County_Level_Presidential_Results_04-20.csv',
'state': './US_State_Level_Presidential_Results_04-20.csv',
'demographic': './US_Demographic_Presidential_Results_04-16.csv'
}
var weburls = {
'county': 'https://raw.githubusercontent.com/psthomas/election-vis/master/US_County_Level_Presidential_Results_04-20.csv',
'state': 'https://raw.githubusercontent.com/psthomas/election-vis/master/US_State_Level_Presidential_Results_04-20.csv',
'demographic': 'https://raw.githubusercontent.com/psthomas/election-vis/master/US_Demographic_Presidential_Results_04-16.csv'
}
var urls = weburls; //locurls;
//Formatting Functions
var pctFormat = d3.format(".2%");
var thsdFormat = d3.format(",");
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//Create SVG
var 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 + ")");
//Year Title
var title = svg.append("text")
.attr("class", "title")
.attr("dy", height-10)
.attr("dx", ".35em");
var demtext = svg.append("text")
.attr("class", "party")
.attr("dy", height-50)
.attr("dx", 243);
var reptext = svg.append("text")
.attr("class", "party")
.attr("dy", height-14)
.attr("dx", 243);
//Define static scales
var xScale = d3.scaleLinear()
.domain([-100, 100])
.range([0, width]);
var yScale = d3.scaleLinear()
.domain([0, 100])
.range([height, 0]);
//Base the color scale on the democratic margin.
var colorScale = d3.scaleLinear()
.domain([-80, 0, 80])
.range(['#EF3B2C', '#885ead', '#08519C'])
.interpolate(d3.interpolateRgb);
//Define x, y axes
var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);
//Append Axes
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("y", "3em")
.attr("x", width/2)
.text("Democratic Margin (%)");
svg.append("g")
.attr("class", "axis")
.call(yAxis)
.attr("transform", "translate(" + (width/2) + ",0)")
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "-3.75em")
.style("text-anchor", "end")
.text("Turnout (%VAP)");
//Statically place tooltip:
var tooltip = d3.select("#formholder")
.append("div")
.style("position", "absolute")
.style("visibility", "hidden")
.attr("class", "tooltip");
//Adds event listener
d3.select('#inds').on("change", dropdownRender);
function dropdownRender() {
var sel = document.getElementById("inds");
selection = sel.options[sel.selectedIndex].value; //Sets a global
switch (selection) {
case 'county':
renderCounties();
break;
case 'state':
renderStates();
break;
case 'race':
renderDemographic('race');
//Eventually renderDemographic('race');
break;
case 'gender':
renderDemographic('gender');
break;
case 'age':
renderDemographic('age');
break;
case 'education':
renderDemographic('education');
break;
}
}
// Helper functions:
function getYearData(dataset, year) {
for (var i=0; i<dataset.length; i++) {
if (Number(dataset[i].key) === year) {
return dataset[i].values;
}
}
}
function copyObj(original) {
return JSON.parse(JSON.stringify(original));
}
// d3.select('#searchform').onSubmit( function() {
// handleClick();
// return false;
// });
function removeSearch() {
document.getElementById("myVal").value= '';
handleClick();
}
function handleClick(event){
currentSearch = document.getElementById("myVal").value;
var words = currentSearch.split(",").map(function(s) { return s.trim() });
//Modifies global search variable, also used in update()
searchTerms = RegExp(words.join('|'), "g"); //gi is case insensitive global, g is just global
//svg.selectAll
d3.selectAll("circle").each(function(d) {
var circle = d3.select(this);
switch (selection) {
case 'county':
var field = d.county;
var count = d.county_num;
break;
case 'state':
var field = d.state;
var count = d.num_state;
break;
case 'race':
case 'gender':
case 'age':
case 'education':
var field = d.group;
var count = d.num_group;
break;
}
if ( (field.search(searchTerms) != -1) || (currentSearch == "") ) { //(d.county.search(searchTerms) != -1)
circle.style('pointer-events', 'auto');
circle.attr("fill", colorScale(((d.num_dem-d.num_rep)/count)*100));
circle.style("stroke-opacity", 1);
} else {
circle.style('pointer-events', 'none');
circle.attr("fill", "rgba(192,192,192,0.05)");
circle.style("stroke-opacity", 0);
}
});
return false; //Don't reload page
}
function renderCounties() {
if (cache.counties) {
build(cache.counties);
} else {
d3.csv(urls.county, parseRows, function(error, data) {
if (error) {throw error};
//Update cache:
cache.counties = data;
build(data);
});
}
function parseRows(d) {
return {'county': d.county_name + ', ' + d.state, 'state': d.state, 'county_num': +d.county_num, 'turnout': +d.turnout,
'num_rep': +d.rep_num, 'num_dem': +d.dem_num, 'year': +d.year, 'state_electoral_votes': +d.state_electoral_votes,
'vap': +d.vap, 'id': d.fips_code, 'dem_margin': +d.dem_margin*100};
}
function tooltipOn(d) {
tooltip.style("visibility", "visible")
.html(
d.county + "<br>" +
"County: D: " + pctFormat(d.num_dem/d.county_num) +
" R: " + pctFormat(d.num_rep/d.county_num) + "<br>" +
"Turnout: " + pctFormat(d.turnout) + "<br>" +
"Voters: " + thsdFormat(Math.round(d.county_num)) + "<br>" +
"State: D: " + pctFormat(d.num_state_dem/d.num_state) +
" R: " + pctFormat(d.num_state_rep/d.num_state) + "<br>" );
}
function build(data) {
// Build state data sums
var stateData = d3.nest()
.key(function(d) { return d.year; })
.key(function(d) { return d.state; })
.rollup(function(v) { return {
'num_state': d3.sum(v, function(d) { return d.county_num; }),
'num_state_dem': d3.sum(v, function(d) { return d.num_dem; }),
'num_state_rep': d3.sum(v, function(d) { return d.num_rep; }),
}; })
.object(data);
// Add the state level data to each county object
data.forEach(function(d) {
d.num_state = stateData[d.year][d.state]['num_state'],
d.num_state_dem = stateData[d.year][d.state]['num_state_dem'],
d.num_state_rep = stateData[d.year][d.state]['num_state_rep']
});
var dataset = d3.nest()
.key(function(d) { return +d.year; })
.sortValues(function(a,b) { return b.county_num - a.county_num; } ) //Bring smallest to front
.object(data);
//.entries(data);
var years = Object.keys(dataset).map(Number);
years.sort()
year = year ? year : years[0];
//Create a copy, so it can be edited on drag:
//var yearData = Object.assign([], getYearData(dataset, year));
//var yearData = copyObj(getYearData(dataset, year));
var yearData = copyObj(dataset[String(year)]);
//Data is just array of all objects from csv, used to find max of all years
var rScale = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {return Math.sqrt(d.county_num/Math.PI); })]) //Area proportional to votes
.range([1, 35]); //2,60 2, 30
var rScale_electoral = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return Math.sqrt((d.county_num/d.num_state)*d.state_electoral_votes/Math.PI); //Area proportional to electoral votes
})])
.range([1, 35]);
var rScale_vpi = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
var county_vpi = (d.county_num/d.num_state) * (d.state_electoral_votes/(Math.abs(d.num_state_dem-d.num_state_rep)));
// Using VAP instead
//var county_vpi = (d.vap/d.num_state) * (d.state_electoral_votes/(Math.abs(d.num_state_dem-d.num_state_rep)));
return Math.sqrt(county_vpi/Math.PI); //Area proportional to VPI
})])
.range([1, 35]); //2,60 2, 30
function upclick() {
year += 4;
if (year > years[years.length - 1]) {
year = years[0]
}
//Assign to new object, update circles:
getYearData(dataset, year);
//yearData = Object.assign([], getYearData(dataset, year));
yearData = copyObj(dataset[String(year)]);
update(yearData, year);
}
function downclick() {
year -= 4;
if (year < years[0]) {
year = years[years.length - 1];
}
//Assign to new object, update:
//yearData = Object.assign([], getYearData(dataset, year));
//yearData = copyObj(getYearData(dataset, year));
yearData = copyObj(dataset[String(year)]);
update(yearData, year);
}
d3.select('#upclick').on("click", upclick);
d3.select('#downclick').on("click", downclick);
function getRadioScaled(d) {
var checked = document.querySelector('input[name="area"]:checked').value;
if (checked === "electoral") {
return rScale_electoral(Math.sqrt((d.county_num/d.num_state)*d.state_electoral_votes/Math.PI));
// d.county_num Math.pow(d.county_num, 0.6) Math.sqrt(d.county_num/Math.PI) Math.sqrt(d *4/Math.PI)
} else if (checked === "vpi") {
//voter power index:
//http://www.dailykos.com/story/2016/12/19/1612252/-Voter-Power-Index-Just
//-How-Much-Does-the-Electoral-College-Distort-the-Value-of-Your-Vote
// Using county_num
var county_vpi = (d.county_num/d.num_state) * (d.state_electoral_votes/(Math.abs(d.num_state_dem-d.num_state_rep)));
// using VAP:
//var county_vpi = (d.vap/d.num_state) * (d.state_electoral_votes/(Math.abs(d.num_state_dem-d.num_state_rep)));
return rScale_vpi(Math.sqrt(county_vpi/Math.PI));
} else {
//Area proportional to number of voters
return rScale(Math.sqrt(d.county_num/Math.PI));
}
}
function updateAreas(event){
d3.selectAll("circle").transition()
.duration(1000) //750;
.attr("r", function(d) {
return getRadioScaled(d);
});
}
d3.select("#areaform")
.on("click", function () {
return updateAreas();
});
//Dragging behavior
//https://bl.ocks.org/mbostock/6123708
var drag = d3.drag()
.on("drag", dragged)
.on("end", ended);
function dragged(d) {
//Remove transitions temporarily
d3.selectAll("circle").transition();
//Issue when dragged across 0 threshold, county_num = 0
if (d3.event.y >= height) {
return;
}
//Relocate circle with mouse
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
//Avoid case of no shift
if (d.x === undefined || d.y === undefined) {
return;
}
var newMargin = xScale.invert(d.x)/100,
newTurnout = yScale.invert(d.y)/100, //Math.abs() d.y
oldTurnout = d.turnout,
oldMargin = (d.num_dem-d.num_rep)/d.county_num,
marginChange = newMargin-oldMargin,
oldDfrac = d.num_dem/d.county_num,
oldRfrac = d.num_rep/d.county_num,
oldNumDem = d.num_dem,
oldNumRep = d.num_rep;
//Recalculate fractions based on margin change
//Half goes to each side, zero sum
dfrac = oldDfrac + marginChange/2;
rfrac = oldRfrac - marginChange/2;
//Add increses in turnout to county_num
d.county_num = newTurnout*d.vap;
// Recalculate based on margin change first, assumes
// margin changes are zero sum between parties.
d.num_dem = dfrac*d.county_num;
d.num_rep = rfrac*d.county_num;
d.turnout = newTurnout;
//Change state level data
d.num_state += (newTurnout - oldTurnout)*d.vap //Multiply turnout change times County Voting Age population
d.num_state_dem += d.num_dem - oldNumDem; //Update state dem and rep counts
d.num_state_rep += d.num_rep - oldNumRep;
//Call the tooltip function each time to update.
tooltipOn(d);
//Update all other counties in state
for (var i = 0; i<yearData.length; i++) {
if (yearData[i].state === d.state) {
yearData[i].num_state = d.num_state;
yearData[i].num_state_dem = d.num_state_dem;
yearData[i].num_state_rep = d.num_state_rep;
}
}
//Update score as well:
updateScore(yearData);
}
function ended(d) {
// Modify the yeardata, then call update(yearData, d.year);
for (var i = 0; i<yearData.length; i++) {
if (yearData[i].state === d.state) {
yearData[i].num_state = d.num_state;
yearData[i].num_state_dem = d.num_state_dem;
yearData[i].num_state_rep = d.num_state_rep;
}
}
update(yearData, d.year);
}
function updateScore(yearData) {
//Could get this data directly from dataframe,
//but want to calculate so can be updated easily on drag.
var sums = [0,0,0];
var electoral_sums = [[],0,0];
for (var i=0; i<yearData.length; i++) {
sums[0] += yearData[i].num_dem;
sums[1] += yearData[i].num_rep;
sums[2] += yearData[i].county_num;
//Sum up electoral votes for each unique state
}
// console.log(yearData);
var states = [];
var stateYearData = yearData.filter( function(current) {
//console.log(current);
//return states.indexOf(current.state)
if (states.indexOf(current.state) === -1) {
states.push(current.state);
return true;
}
return false;
});
for (var i = 0; i<stateYearData.length; i++) {
var stateName = stateYearData[i].state;
var currentYear = stateYearData[i].year;
if (currentYear === 2016 && ['ME','NE'].indexOf(stateName) !== -1) { //['ME','NE'].indexOf(stateName) !== -1 (stateName === 'ME' || stateName === 'NE')
//console.log('entered');
//Handle split states
// electoral_sums[1] += 3; // ME + NB
// electoral_sums[2] += 6; // ME + NB
//Will be entered twice, so give 1.5, 3 each entrance instead:
electoral_sums[1] += 1.5; // ME + NB
electoral_sums[2] += 3; // ME + NB
//electoral_sums[0].push(stateName === 'ME' ? 'NE' : 'ME'); //Make sure both states are added
//electoral_sums[0] = electoral_sums[0].concat(['ME','NE']);
} else if (currentYear === 2008 && stateName === 'NE' ) {
electoral_sums[1] += 1;
electoral_sums[2] += 4;
} else if (stateYearData[i].num_state_dem > stateYearData[i].num_state_rep ) {
//electoral_sums[1] is dems
electoral_sums[1] += stateYearData[i].state_electoral_votes;
} else {
electoral_sums[2] += stateYearData[i].state_electoral_votes;
}
}
var dfrac = sums[0]/sums[2],
rfrac = sums[1]/sums[2];
//update dfrac rfrac text, update color background
demtext.text('D ' + pctFormat(dfrac) + ' ' + electoral_sums[1])
reptext.text('R ' + pctFormat(rfrac) + ' ' + electoral_sums[2])
if (electoral_sums[1] > electoral_sums[2]) {
demtext.style('fill', '#bbb');
reptext.style('fill', null);
} else {
demtext.style('fill', null);
reptext.style('fill', '#bbb');
}
//Optional, set background color based on winner
// var backColor = dfrac > rfrac ? colorScale(5) : colorScale(-5);
// //var backColor = colorScale((dfrac-rfrac)*100);
// d3.selectAll('svg')
// .style('background-color', backColor);
}
function update(yearData, year) {
//Change D,R scores:
updateScore(yearData);
//Update title
title.text(year);
var circles = svg.selectAll("circle")
.data(yearData, function(d) { return d.id ; }); // Key for object constancy: https://bost.ocks.org/mike/constancy/
// .data(yearData, function(d) {
// if (d.state === 'MA') {
// console.log(d.id);
// }
// return d.id;
// });
circles.exit().remove();
circles.enter().append("circle")
.on("mouseover", tooltipOn) //Add tooltip before transition
.on("mouseout", function(d){return tooltip.style("visibility", "hidden");})
.call(drag)
.attr("class", "circle")
.merge(circles)
.transition()
.duration(1000) //750; 1000
.attr("cx", function(d) {
return xScale(((d.num_dem-d.num_rep)/d.county_num)*100);
})
.attr("cy", function(d) {
return yScale(d.turnout*100);
})
.attr("r", function(d) {
return getRadioScaled(d);
})
.attr("fill",function(d){
if (d.county.search(searchTerms) != -1) {
return colorScale(((d.num_dem-d.num_rep)/d.county_num)*100);
}else {
return "rgba(192,192,192,0.05)";
}
});
}
function initialize(yearData, year) {
//Change D,R scores:
updateScore(yearData);
//Update title
title.text(year);
var circles = svg.selectAll("circle")
.data(yearData, function(d) { return d.id ; });
// .data(yearData, function(d) {
// if (d.state === 'MA') {
// console.log(d.id);
// }
// return d.id;
// }); // Key for object constancy: https://bost.ocks.org/mike/constancy/
circles.exit().remove();
//Create any new circles
circles.enter().append("circle")
.attr("class", "circle")
.attr("cx", function(d) {
return xScale(((d.num_dem-d.num_rep)/d.county_num)*100);
})
.attr("cy", function(d) {
return yScale(d.turnout*100);
})
.attr("r", function(d) {
//return rScale(Math.sqrt(d.county_num/Math.PI));
return getRadioScaled(d);
})
.attr("fill",function(d){
if (d.county.search(searchTerms) != -1) {
return colorScale(((d.num_dem-d.num_rep)/d.county_num)*100);
}else {
return "rgba(192,192,192,0.05)";
}
})
.call(drag)
.on("mouseover", tooltipOn)
.on("mouseout", function(d){return tooltip.style("visibility", "hidden");});
}
//Initialize scatterplot
initialize(yearData, year);
//update(yearData, year); //Works, but transition is weird.
} //);
}
function renderStates() {
if (cache.states) {
build(cache.states);
} else {
d3.csv(urls.state, parseRows, function(error, data) {
if (error) {throw error};
//Update cache:
cache.states = data;
build(data);
});
}
function tooltipOn(d) {
tooltip.style("visibility", "visible")
.html(
"State: " + d.state + "<br>" +
" D: " + pctFormat(d.num_dem/d.num_state) +
" R: " + pctFormat(d.num_rep/d.num_state) + "<br>" +
"Turnout: " + pctFormat(d.turnout) + "<br>" +
"Voters: " + thsdFormat(Math.round(d.num_state)) + "<br>")
}
function parseRows(d) {
return {'state': d.state, 'id': d.state, 'num_state': +d.state_num, 'turnout': +d.state_num/+d.vap,
'num_rep': +d.rep_num, 'num_dem': +d.dem_num, 'year': +d.year, 'state_electoral_votes': +d.state_electoral_votes,
'vap': +d.vap, 'dem_margin': (+d.dem_num - +d.rep_num) / +d.state_num};
}
function build(data) {
var dataset = d3.nest()
.key(function(d) { return +d.year; })
.sortValues(function(a,b) { return b.num_state - a.num_state; } ) //Bring smallest to front
.object(data);
//.entries(data);
var years = Object.keys(dataset).map(Number);
years.sort()
//var year = years[0];
year = year ? year : years[0];
//Create a copy, so it can be edited on drag:
var yearData = copyObj(dataset[String(year)]);
//Data is just array of all objects from csv, used to find max of all years
var rScale = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {return Math.sqrt(d.num_state/Math.PI); })]) //Area proportional to votes
.range([1, 35]); //2,60 2, 30
var rScale_electoral = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return Math.sqrt(d.state_electoral_votes/Math.PI); //Area proportional to electoral votes
})])
.range([1, 35]);
var rScale_vpi = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
var county_vpi = d.state_electoral_votes/(Math.abs(d.num_dem-d.num_rep));
// Using VAP instead
//var county_vpi = (d.vap/d.num_state) * (d.state_electoral_votes/(Math.abs(d.num_state_dem-d.num_state_rep)));
return Math.sqrt(county_vpi/Math.PI); //Area proportional to VPI
})])
.range([1, 35]); //2,60 2, 30
function upclick() {
year += 4;
if (year > years[years.length - 1]) {
year = years[0]
}
//Assign to new object, update circles:
getYearData(dataset, year);
//yearData = Object.assign([], getYearData(dataset, year));
yearData = copyObj(dataset[String(year)]);
update(yearData, year);
}
function downclick() {
year -= 4;
if (year < years[0]) {
year = years[years.length - 1];
}
//Assign to new object, update:
//yearData = Object.assign([], getYearData(dataset, year));
//yearData = copyObj(getYearData(dataset, year));
yearData = copyObj(dataset[String(year)]);
update(yearData, year);
}
d3.select('#upclick').on("click", upclick);
d3.select('#downclick').on("click", downclick);
function getRadioScaled(d) {
var checked = document.querySelector('input[name="area"]:checked').value;
if (checked === "electoral") {
return rScale_electoral(Math.sqrt(d.state_electoral_votes/Math.PI));
// d.county_num Math.pow(d.county_num, 0.6) Math.sqrt(d.county_num/Math.PI) Math.sqrt(d *4/Math.PI)
} else if (checked === "vpi") {
//voter power index:
//http://www.dailykos.com/story/2016/12/19/1612252/-Voter-Power-Index-Just
//-How-Much-Does-the-Electoral-College-Distort-the-Value-of-Your-Vote
// Using county_num
var county_vpi = d.state_electoral_votes/(Math.abs(d.num_dem-d.num_rep));
// using VAP:
//var county_vpi = (d.vap/d.num_state) * (d.state_electoral_votes/(Math.abs(d.num_state_dem-d.num_state_rep)));
return rScale_vpi(Math.sqrt(county_vpi/Math.PI));
} else {
//Area proportional to number of voters
return rScale(Math.sqrt(d.num_state/Math.PI));
}
}
function updateAreas(event){
d3.selectAll("circle").transition()
.duration(1000) //750;
.attr("r", function(d) {
return getRadioScaled(d);
});
}
d3.select("#areaform")
.on("click", function () {
return updateAreas();
});
//Dragging behavior
//https://bl.ocks.org/mbostock/6123708
var drag = d3.drag()
.on("drag", dragged)
.on("end", ended);
function dragged(d) {
//Remove transitions temporarily
d3.selectAll("circle").transition();
//Issue when dragged across 0 threshold, county_num = 0
if (d3.event.y >= height) {
return;
}
//Relocate circle with mouse
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
//Avoid case of no shift
if (d.x === undefined || d.y === undefined) {
return;
}
var newMargin = xScale.invert(d.x)/100,
newTurnout = yScale.invert(d.y)/100, //Math.abs() d.y
oldTurnout = d.turnout,
oldMargin = (d.num_dem-d.num_rep)/d.num_state,
marginChange = newMargin-oldMargin,
oldDfrac = d.num_dem/d.num_state,
oldRfrac = d.num_rep/d.num_state,
oldNumDem = d.num_dem,
oldNumRep = d.num_rep;
//Recalculate fractions based on margin change
//Half goes to each side, zero sum
dfrac = oldDfrac + marginChange/2;
rfrac = oldRfrac - marginChange/2;
//Add increses in turnout to county_num
d.num_state = newTurnout*d.vap;
// Recalculate based on margin change first, assumes
// margin changes are zero sum between parties.
d.num_dem = dfrac*d.num_state;
d.num_rep = rfrac*d.num_state;
d.turnout = newTurnout;
//Call the tooltip function each time to update.
tooltipOn(d);
//Update score as well:
updateScore(yearData);
}
function ended(d) {
//No longer needed, as this is at state level?:
// Modify the yeardata, then call update(yearData, d.year);
for (var i = 0; i<yearData.length; i++) {
if (yearData[i].state === d.state) {
yearData[i].num_state = d.num_state;
}
}
update(yearData, d.year);