-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex2.html
More file actions
601 lines (515 loc) · 25.2 KB
/
index2.html
File metadata and controls
601 lines (515 loc) · 25.2 KB
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
<!doctype html>
<html lang="en">
<head>
<title>Prosper Loan Analysis</title>
<meta charset="utf-8">
<script src="d3.min.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
// Set the margins for use with the svgs
// NB the dimensions of the bl.ocks window is 962 * 502
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 962 - margin.left - margin.right,
height = 502 - margin.top - margin.bottom;
// set the dimensions for the buttons - this influence the buttonBuffer
var buttonWidth = 100,
buttonHeight = 19,
buttonSpace = 1,
buttonX0 = (width - (2* buttonWidth) - 2),
buttonY0 = 2
buttonBuffer = (2* buttonWidth) +10;
// Create percentage format variable for use in axes
var formatAsPercentage = d3.format("1%");
// Create colors (52) for use with the 52 different occupations - might change
var colors = ["#8dd3c7","#ffffb3","#bebada","#fb8072","#80b1d3","#fdb462","#b3de69","#fccde5","#d9d9d9",
"#bc80bd","#ccebc5","#ffed6f","#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f",
"#e5c494","#b3b3b3","#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628",
"#f781bf","#c9d9d9","#b7fcfd","#d545f9","#ccece6","#99d8c9","#66c2a4","#41ae76","#238b45",
"#006d2c","#11441b","#bba7fb","#ecedb0","#d0d1e6","#a6bddb","#67a9cf","#3690c0","#02818a",
"#016c59","#01cd36","#f137fb","#e267f2","#d0d1e6","#a6bddb","#74a9cf","#3690c0","#0570b0"];
function draw(data) {
/*
//take this out to save space on bl.ocks - duplicated with title
// put it back in if using in normal html
d3.select("#container")
.append('h1')
.attr('class','title')
.text('Average APR by occupation and income level');
*/
// Manipulate the data
// created a nested function, grouping the data by Occupation group.
var nested = d3.nest()
.key(function(d){
return d.OccGroup;
}
).sortKeys(d3.ascending)
.entries(data);
// created nestedIncome variable to average the APR across all occupations
// use this to create the average APR line and circles only.
var nestedIncome = d3.nest()
.key(function(d){
return d.income;
})
.rollup(function(leaves){
var meanApr = d3.mean(leaves, function(d) {
return d['apr'];
});
var total = d3.sum(leaves, function(d){
return d['N'];
});
return {"meanApr": meanApr,
'N':total};
})
.entries(data);
// create linesArray which reshapes the data into easier format to use with linedraw function
var linesArray = [];
for (i in nested){
pathInfo = [];
for (j in nested[i].values){
pathInfo.push({'id': nested[i].values[j].id,
'apr': nested[i].values[j].apr,
'income': nested[i].values[j].income});
}
linesArray.push({'key': nested[i].key,
'values': pathInfo});
}
// Create svg variable to use with D3 code
var svg = d3.select("#container")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("class", "svg");
// Create myChart variable within the svg item to house the chart. 'g' is just an arbitrary containing child element in SVG
// equivalent to 'div' in HTML
var myChart = svg.append("g")
.attr("transform","translate(" + margin.left +"," + margin.top +")")
.attr("width", width)
.attr('height', height)
.attr("class", "chart");
// draw the Occupation text on the chart
myChart.append('text')
.attr("class", "occupTitle")
.attr('x', (width-buttonBuffer)/2)
.attr('y', 45)
.style('text-anchor','middle')
.text("Run animation or click on Occupation");
// Create a set of unique occupations called 'occupations' by adding to it.
var occupations = d3.set();
data.forEach(function(d){
occupations.add(d["OccGroup"])
});
// then create an array of just the values in this set - makes the rest of the code much easier
var uniqueOccupations = occupations.values();
// sort them alphabetically
uniqueOccupations.sort(d3.ascending);
// the occupations are categorical, so we need an ordinal scale for the colors.
var colorScale = d3.scale.ordinal()
.domain(d3.extent(data, function(d){
return d.OccGroup;
}))
.range(colors);
// the x axis data is categorical, so we need an ordinal scale.
// Change the padding if the data is too close to edges
var xScale = d3.scale.ordinal()
.domain(["$1-25k", "$25-50k", "$50-75k", "$75-100k", "$100k+"])
.rangePoints([0,(width - buttonBuffer-50)],1);
// create the x-axis object (note - not added yet, just defined the variable)
var xAxis = d3.svg.axis()
.scale(xScale)
.tickSize(5)
.orient("bottom"); // this specifies the orientation of labels relative to the axis
// Add the x-axis in it's own 'g' group.
myChart.append("g")
.attr("transform","translate(0," + height + ")")
.attr("class","x axis")
.call(xAxis)
.append('text')
.attr("x", (width - buttonBuffer-50))
.attr("y", -6)
.style("text-anchor","end")
.text("Income Bracket");
// construct the y axis scale. This is linear as it is a range of apr values.
var yScale = d3.scale.linear()
.domain([0,d3.max(data, function(d){
return d.apr;
})])
.range([height,0])
.nice();
// create the y-axis object (note - not added yet, just defined)
var yAxis = d3.svg.axis()
.scale(yScale)
.tickSize(5)
.tickFormat(formatAsPercentage)
.orient("left"); // this specifies the orientation of labels to the axis
// function for creating the y grid lines
function make_y_grids() {
return d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(7);
}
// Add the y-axis in it's own 'g' group.
myChart.append("g")
.attr("class","y axis")
.call(yAxis)
.append('text')
.attr('transform', "rotate(-90)")
.attr('y', 6)
.attr('x', -4)
.attr('dy', ".71em")
.style('text-anchor','end')
.style('fill','black')
.text('Average Borrower APR');
// Draw the y Grid lines
myChart.append("g")
.attr("class", "grid")
.call(make_y_grids()
.tickSize(buttonBuffer-width, 0, 0)
.tickFormat("")
);
// create a scale for the radius of the circles
var rScale = d3.scale.sqrt()
.domain([0,d3.max(data, function(d){
return d.N;
})])
.range([1,30]);
// make button for the animation
var animateButton = svg.append('g')
.attr('class', 'animateButton')
.style('cursor','pointer')
.on('click', function(d){
animationLoop();
});
animateButton.append('rect')
.attr('x', 50)
.attr('y', 450)
.attr('rx',5)
.attr('ry', 5)
.attr('width', 90)
.attr('height', 20)
.attr('fill','#7777BB');
animateButton.append('text')
.attr('class','animateText')
.attr('x', 56)
.attr('y', 464)
.text('Run animation')
.attr('fill','white')
.attr('font-family','sans-serif')
.attr('font-size', 12);
// make button to show all
var showAllButton = svg.append('g')
.attr('class', 'showAllButton')
.style('cursor','pointer')
.on('click', function(){
lineDraw(linesArray, lineColor = 'red', lineOpacity = 0.15);
});
debugger;
showAllButton.append('rect')
.attr('x', 150)
.attr('y', 450)
.attr('rx',5)
.attr('ry', 5)
.attr('width', 90)
.attr('height', 20)
.attr('fill','#7777BB');
showAllButton.append('text')
.attr('class','showAllText')
.attr('x', 156)
.attr('y', 464)
.text('Show all')
.attr('fill','white')
.attr('font-family','sans-serif')
.attr('font-size', 12);
// make buttons for the occupations
// set the colors for interaction
var defaultColor= "#7777BB";
var hoverColor= "#0000ff";
var pressedColor= "#000077";
// first make a container for the group of buttons
var allButtons= svg.append("g")
.attr("id","allButtons");
// creat a group for each button (rect and text)
var buttonGroups= allButtons.selectAll("g.button")
.data(uniqueOccupations)
.enter()
.append("g")
.attr("class","button")
.style("cursor","pointer")
.on("click",function(d) {
updateButtonColors(d3.select(this), d3.select(this.parentNode));
update(d);
})
.on("mouseover", function() {
if (d3.select(this).select("rect").attr("fill") != pressedColor) {
d3.select(this)
.select("rect")
.attr("fill",hoverColor);
}
})
.on("mouseout", function() {
if (d3.select(this).select("rect").attr("fill") != pressedColor) {
d3.select(this)
.select("rect")
.attr("fill",defaultColor);
}
});
buttonGroups.append("rect")
.attr("class","buttonRect")
.attr('fill',defaultColor)
.attr("width",buttonWidth)
.attr("height",buttonHeight)
.attr("x", function(d,i){
return (buttonWidth+5) * Math.floor(i/25) + buttonX0;
} )
.attr("y",function(d,i){
return buttonY0 +(buttonHeight + buttonSpace)*(i%25);
});
//adding text to each button group, centered within the button rect
buttonGroups.append("text")
.attr("class","buttonText")
.attr('font-family','sans-serif')
.attr('fill','white')
.attr('font-size',10)
.attr("x", function(d,i){
return (buttonWidth+5) * Math.floor(i/25) + buttonX0 +10 ;
})
.attr("y", function(d,i){
return buttonY0 + (buttonHeight + buttonSpace)*(i%25) + buttonHeight/2;
})
//.attr("text-anchor","middle")
.text(function(d) {
return d;
});
function updateButtonColors(button, parent) {
parent.selectAll("rect")
.attr("fill",defaultColor);
button.select("rect")
.attr("fill",pressedColor);
}
// create the circles for the average APR
var avgCircles = svg.selectAll('.averageCircle')
.data(nestedIncome)
.enter()
.append('circle')
.attr('class','averageCircle')
.attr('cx', function(d){
return xScale(d.key) + margin.left;
})
.attr('cy', function(d){
return yScale(d.values.meanApr) + margin.top;
})
.attr('r', function(d){
return rScale(d.values.N);
})
.style('fill', "black")
.style('opacity', 0.15)
.on("mouseover", function(d) {
tooltip.transition()
.duration(200)
.style("opacity", 0.9);
tooltip.html("Average" + "<br>"
+ "Income Group: " + d.key + "<br>"
+ "Mean APR: " + d3.format(".1%")(d.values.meanApr))
.style('font-size',"10pt")
.style("left", (d3.event.pageX + 5) + "px")
.style("top", (d3.event.pageY - 28) + "px")
.style("background-color","light-grey");
})
.on("mouseout", function(d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
function showCircleScale() {
// want to show 3 circles, with sample sizes for when they are selected
var sizes = [1000, 2000, 4000, 8000];
myChart.append('text')
.attr('x',300 - rScale(sizes[0]))
.attr('y',yScale(0.11))
.text('Sample sizes');
var scaleCircles = myChart.selectAll('scaleCircleG')
.data(sizes)
.enter()
.append('g')
.attr('class','scaleCircle');
scaleCircles.append('circle')
.attr('class','scaleCircleCircle')
.attr('cx', function(d,i) {
return (i*80) +300;
})
.attr('cy', yScale(0.075))
.attr('r',function(d){
return rScale(d);
})
.attr('fill', 'red');
scaleCircles.append('text')
.attr('class','scaleCircleText')
.attr('x',function(d,i) {
return (i*80) +300;
})
.attr('y', yScale(0.03))
.text(function(d){
return d3.format("0,000")(d);
})
.attr('text-anchor','middle');
}
showCircleScale();
// add the tooltip area to the div element with id 'container'
var tooltip = d3.select('#container')
.append("div")
.attr("class", "tooltip")
.style("width", "180px")
.style('height',"60px")
.style("opacity", 0);
//add a selected circle variable
var selectedCircle = svg.append('circle')
.attr('class','selectedCircle')
.attr('cx',100)
.attr('cy',300)
.attr('r',0);
// create function to plot the circles - note, this is within the draw function
function plot_points(occupation_data, circleColor, circleOpacity) {
// bind the data to the circles and enter them - using data, not nested.
var circles = svg.selectAll('.plottedCircle')
.data(occupation_data, function(d){
return d['id'];
});
circles.exit()
.remove();
circles.enter()
.append('circle')
.attr('class','plottedCircle')
.attr('cx', function(d){
return xScale(d.income) + margin.left;
})
.attr('cy', function(d){
return yScale(d.apr) + margin.top;
})
.attr('r', function(d){
return rScale(d.N);
})
.style('fill', circleColor)
.style('opacity', circleOpacity)
.on("mouseover", function(d) {
tooltip.transition()
.duration(200)
.style("opacity", .9);
tooltip.html(d.OccGroup + "<br>"
+ "Income Group: " + d.income + "<br>"
+ "Mean APR: " + d3.format(".1%")(d.apr) +"<br>"
+ "Sample size: " + d3.format("0,000")(d.N))
.style('font-size',"10pt")
.style("left", (d3.event.pageX + 5) + "px")
.style("top", (d3.event.pageY - 28) + "px")
.style("background-color","white");
selectedCircle.transition()
.duration(200)
.style('opacity', 1.0)
.attr('cx', xScale(d.income) + margin.left)
.attr('cy', yScale(d.apr) + margin.top)
.attr('r', rScale(d.N))
.style('fill',function(d){
return colorScale(parent.OccGroup);
});
})
.on("mouseout", function(d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
selectedCircle.transition()
.duration(500)
.style('opacity',0);
});
}// END of function plot points(data)
// Create function to draw a line for an occupation group
function lineDraw(occupation_data, lineColor, lineOpacity) {
// Create variable to define pixel points of the line
var line = d3.svg.line()
.x(function(d) { return xScale(d.income) + margin.left; })
.y(function(d) { return yScale(d.apr) +margin.top; })
.interpolate("cardinal");
// create the linePath for all the individual occupations
var linePath = d3.select('svg')
.selectAll('.occupLine')
.data(occupation_data, function(d){
return d.key;
});
linePath.enter()
.append('g')
.attr('class','occupLine')
.style('stroke', lineColor);
linePath.exit().remove();
linePath.append('path')
.attr('class','line occupPath')
.attr('d', function(d){
return line(d.values);
})
.style('opacity', lineOpacity);
linePath.exit().remove();
}; // End of function lineDraw(occupation)
function lineDrawAverage(averagedata) {
// now create the linePath for the average - this stays on the screen.
// create slightly different line format to deal with the average data
var averageLine = d3.svg.line()
.x(function(d) { return xScale(d.key) + margin.left; })
.y(function(d) { return yScale(d.values.meanApr) +margin.top; })
.interpolate("linear");
var averageLinePath = d3.select('svg')
.append('path')
.attr('d', averageLine(averagedata))
.attr('stroke','black')
.attr('stroke-width',4)
.attr('fill','none');
} // end of lineDrawAverage function
// define update function, to plot the data for a specific occupation
function update(occupation) {
d3.select(".occupTitle")
.text(occupation);
// first filter the main data to return only datapoints equal to that occupation
occup_points_data = data.filter(function(d){
return d.OccGroup === occupation;
});
// also filter the linesArray for datapoints equal to that occupation
occup_line_data = linesArray.filter(function(d){
return d.key === occupation;
});
plot_points(occup_points_data, circleColor = 'red', circleOpacity = 1); // pass those points to the plot_points function
lineDraw(occup_line_data, lineColor = 'red', lineOpacity = 1); // pass those points to the lineDraw function
lineDraw(linesArray, lineColor = 'red', lineOpacity = 0.15);
}
// first draw the line for the averages
lineDrawAverage(nestedIncome);
lineDraw(linesArray, lineColor = 'red',lineOpacity = 0.2);
function animationLoop() {
// to loop through all occupations, drawing circles and points:
occup_idx = 0
var occupation_interval = setInterval(function(){
update(uniqueOccupations[occup_idx]);
occup_idx++;
if (occup_idx >= uniqueOccupations.length) {
clearInterval(occupation_interval);
var circles = plot_points([], circleColor ="red", circleOpacity = 0.0);
var lines = lineDraw(linesArray, lineColor = 'red', lineOpacity = 0.2);
// next bit of code re-styles the last line that was written (i.e. it wasn't part of the 'enter')
d3.selectAll('.occupPath')
.style('opacity', 0.2);
d3.select('.occupTitle')
.text('Run animation or click on Occupation');
}
}, 500);
} // END of function animationLoop
};// END of function draw(data
</script>
</head>
<body>
<div id="container">
</div>
<script type="text/javascript">
//Use D3 to load the CSV file and pass the contents of it to the draw function
d3.csv("loans_clean.csv", function(d) {
d['N'] = +d['N'];
return d},
draw);
</script>
</body>
</html>