-
Notifications
You must be signed in to change notification settings - Fork 0
/
newindex.html
544 lines (449 loc) · 16.5 KB
/
newindex.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
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<style>
.area {
fill: steelblue;
clip-path: url(#clip);
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
</style>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="/bubble_chart.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.js"></script>
<title> eco-vis </title>
</head>
<body>
<div class="container">
<h1> eco-visualisation </h1>
<h2> homepage </h2>
<br>
<div id="toolbar">
<a href="#" id="all" class="button active">All Offices</a>
<a href="#" id="year" class="button">Offices By Location</a>
</div>
<div id="vis"></div>
</div>
<script>
//tooltip code
function floatingTooltip(tooltipId, width) {
// Local variable to hold tooltip div for
// manipulation in other functions.
var tt = d3.select('body')
.append('div')
.attr('class', 'tooltip')
.attr('id', tooltipId)
.style('pointer-events', 'none');
// Set a width if it is provided.
if (width) {
tt.style('width', width);
}
// Initially it is hidden.
hideTooltip();
/*
* Display tooltip with provided content.
*
* content is expected to be HTML string.
*
* event is d3.event for positioning.
*/
function showTooltip(content, event) {
tt.style('opacity', 1.0)
.html(content);
updatePosition(event);
}
/*
* Hide the tooltip div.
*/
function hideTooltip() {
tt.style('opacity', 0.0);
}
/*
* Figure out where to place the tooltip
* based on d3 mouse event.
*/
function updatePosition(event) {
var xOffset = 20;
var yOffset = 10;
var ttw = tt.style('width');
var tth = tt.style('height');
var wscrY = window.scrollY;
var wscrX = window.scrollX;
var curX = (document.all) ? event.clientX + wscrX : event.pageX;
var curY = (document.all) ? event.clientY + wscrY : event.pageY;
var ttleft = ((curX - wscrX + xOffset * 2 + ttw) > window.innerWidth) ?
curX - ttw - xOffset * 2 : curX + xOffset;
if (ttleft < wscrX + xOffset) {
ttleft = wscrX + xOffset;
}
var tttop = ((curY - wscrY + yOffset * 2 + tth) > window.innerHeight) ?
curY - tth - yOffset * 2 : curY + yOffset;
if (tttop < wscrY + yOffset) {
tttop = curY + yOffset;
}
tt.style({ top: tttop + 'px', left: ttleft + 'px' });
}
return {
showTooltip: showTooltip,
hideTooltip: hideTooltip,
updatePosition: updatePosition
};
}
//end tooltip code
/* bubbleChart creation function. Returns a function that will
* instantiate a new bubble chart given a DOM element to display
* it in and a dataset to visualize.
*
* Organization and style inspired by:
* https://bost.ocks.org/mike/chart/
*
*/
function bubbleChart() {
// Constants for sizing
var width = 1050;
var height = 600;
// tooltip for mouseover functionality
var tooltip = floatingTooltip('gates_tooltip', 240);
// Locations to move bubbles towards, depending
// on which view mode is selected.
var center = { x: width / 2, y: height / 2 };
var yearCenters = {
"Columbia" : { x: width / 5, y: height / 2 },
"Cambodia": { x: 2 * width / 5, y: height / 2 },
"Mauritania": { x: 3 * width / 5, y: height / 2 },
"Niger": { x: 4 * width / 5, y: height / 2 }
};
// X locations of the year titles.
var yearsTitleX = {
"Columbia" : (width / 5) - 80,
"Cambodia" : (2 * width / 5) - 50,
"Mauritania" : 3 * width / 5 + 50,
"Niger" : (4 * width / 5) + 80
};
// Used when setting up force and
// moving around nodes
var damper = 0.102;
// These will be set in create_nodes and create_vis
var svg = null;
var bubbles = null;
var nodes = [];
// Charge function that is called for each node.
// Charge is proportional to the diameter of the
// circle (which is stored in the radius attribute
// of the circle's associated data.
// This is done to allow for accurate collision
// detection with nodes of different sizes.
// Charge is negative because we want nodes to repel.
// Dividing by 8 scales down the charge to be
// appropriate for the visualization dimensions.
function charge(d) {
return -Math.pow(d.radius, 2.0) / 8;
}
// Here we create a force layout and
// configure it to use the charge function
// from above. This also sets some contants
// to specify how the force layout should behave.
// More configuration is done below.
var force = d3.layout.force()
.size([width, height])
.charge(charge)
.gravity(-0.01)
.friction(0.9);
// Nice looking colors - no reason to buck the trend
var fillColor = d3.scale.ordinal()
.domain(['Columbia', 'Cambodia', 'Mauritania', 'Niger'])
.range(['aqua', 'teal', 'blue', 'navy']);
// Sizes bubbles based on their area instead of raw radius
var radiusScale = d3.scale.pow()
.exponent(0.5)
.range([2, 85]);
/*
* This data manipulation function takes the raw data from
* the CSV file and converts it into an array of node objects.
* Each node will store data and visualization values to visualize
* a bubble.
*
* rawData is expected to be an array of data objects, read in from
* one of d3's loading functions like d3.csv.
*
* This function returns the new node array, with a node in that
* array for each element in the rawData input.
*/
function createNodes(rawData) {
// Use map() to convert raw data into node data.
// Checkout http://learnjsdata.com/ for more on
// working with data.
var myNodes = rawData.map(function (d) {
return {
id: d.id,
radius: radiusScale(+d.total_energy),
value: d.total_energy,
name: d.location,
floor: d.floor,
// org: d.organization,
// group: d.group,
// year: d.start_year,
x: Math.random() * 900,
y: Math.random() * 800
};
});
// sort them to prevent occlusion of smaller nodes.
myNodes.sort(function (a, b) { return b.value - a.value; });
return myNodes;
}
/*
* Main entry point to the bubble chart. This function is returned
* by the parent closure. It prepares the rawData for visualization
* and adds an svg element to the provided selector and starts the
* visualization creation process.
*
* selector is expected to be a DOM element or CSS selector that
* points to the parent element of the bubble chart. Inside this
* element, the code will add the SVG continer for the visualization.
*
* rawData is expected to be an array of data objects as provided by
* a d3 loading function like d3.csv.
*/
var chart = function chart(selector, rawData) {
// Use the max total_amount in the data as the max in the scale's domain
// note we have to ensure the total_amount is a number by converting it
// with `+`.
var maxAmount = d3.max(rawData, function (d) { return +d.total_energy; });
radiusScale.domain([0, maxAmount]);
nodes = createNodes(rawData);
// Set the force's nodes to our newly created nodes array.
force.nodes(nodes);
// Create a SVG element inside the provided selector
// with desired size.
svg = d3.select(selector)
.append('svg')
.attr('width', width)
.attr('height', height);
// Bind nodes data to what will become DOM elements to represent them.
bubbles = svg.selectAll('.bubble')
.data(nodes, function (d) { return d.id; });
// Create new circle elements each with class `bubble`.
// There will be one circle.bubble for each object in the nodes array.
// Initially, their radius (r attribute) will be 0.
bubbles.enter().append('circle')
.classed('bubble', true)
.attr('r', 0)
.attr('fill', function (d) { return fillColor(d.name); })
.attr('stroke', function (d) { return d3.rgb(fillColor(d.name)).darker(); })
.attr('stroke-width', 2)
.on('mouseover', showDetail)
.on('mouseout', hideDetail);
// Fancy transition to make bubbles appear, ending with the
// correct radius
bubbles.transition()
.duration(2000)
.attr('r', function (d) { return d.radius; });
// Set initial layout to single group.
groupBubbles();
};
/*
* Sets visualization in "single group mode".
* The year labels are hidden and the force layout
* tick function is set to move all nodes to the
* center of the visualization.
*/
function groupBubbles() {
hideYears();
force.on('tick', function (e) {
bubbles.each(moveToCenter(e.alpha))
.attr('cx', function (d) { return d.x; })
.attr('cy', function (d) { return d.y; });
});
force.start();
}
/*
* Helper function for "single group mode".
* Returns a function that takes the data for a
* single node and adjusts the position values
* of that node to move it toward the center of
* the visualization.
*
* Positioning is adjusted by the force layout's
* alpha parameter which gets smaller and smaller as
* the force layout runs. This makes the impact of
* this moving get reduced as each node gets closer to
* its destination, and so allows other forces like the
* node's charge force to also impact final location.
*/
function moveToCenter(alpha) {
return function (d) {
d.x = d.x + (center.x - d.x) * damper * alpha;
d.y = d.y + (center.y - d.y) * damper * alpha;
};
}
/*
* Sets visualization in "split by year mode".
* The year labels are shown and the force layout
* tick function is set to move nodes to the
* yearCenter of their data's year.
*/
function splitBubbles() {
showYears();
force.on('tick', function (e) {
bubbles.each(moveToYears(e.alpha))
.attr('cx', function (d) { return d.x; })
.attr('cy', function (d) { return d.y; });
});
force.start();
}
/*
* Helper function for "split by year mode".
* Returns a function that takes the data for a
* single node and adjusts the position values
* of that node to move it the year center for that
* node.
*
* Positioning is adjusted by the force layout's
* alpha parameter which gets smaller and smaller as
* the force layout runs. This makes the impact of
* this moving get reduced as each node gets closer to
* its destination, and so allows other forces like the
* node's charge force to also impact final location.
*/
function moveToYears(alpha) {
return function (d) {
// console.log(d);
var target = yearCenters[d.name];
// console.log(d.location);
d.x = d.x + (target.x - d.x) * damper * alpha * 1.1;
d.y = d.y + (target.y - d.y) * damper * alpha * 1.1;
};
}
/*
* Hides Year title displays.
*/
function hideYears() {
svg.selectAll('.year').remove();
}
/*
* Shows Year title displays.
*/
function showYears() {
// Another way to do this would be to create
// the year texts once and then just hide them.
var yearsData = d3.keys(yearsTitleX);
var years = svg.selectAll('.year')
.data(yearsData);
years.enter().append('text')
.attr('class', 'year')
.attr('x', function (d) { return yearsTitleX[d]; })
.attr('y', 40)
.attr('text-anchor', 'middle')
.text(function (d) { return d; });
}
/*
* Function called on mouseover to display the
* details of a bubble in the tooltip.
*/
function showDetail(d) {
// change outline to indicate hover state.
d3.select(this).attr('stroke', 'black');
var content = '<span class="name">Title: </span><span class="value">' +
d.name +
'</span><br/>' +
'<span class="name">Total Energy Usage (KWH): </span><span class="value">' +
addCommas(d.value) +
'</span><br/>' +
'<span class="name">Floor: </span><span class="value">' +
d.floor +
'</span>';
tooltip.showTooltip(content, d3.event);
}
/*
* Hides tooltip
*/
function hideDetail(d) {
// reset outline
d3.select(this)
.attr('stroke', d3.rgb(fillColor(d.name)).darker());
tooltip.hideTooltip();
}
/*
* Externally accessible function (this is attached to the
* returned chart function). Allows the visualization to toggle
* between "single group" and "split by year" modes.
*
* displayName is expected to be a string and either 'year' or 'all'.
*/
chart.toggleDisplay = function (displayName) {
if (displayName === 'year') {
splitBubbles();
} else {
groupBubbles();
}
};
// return the chart function from closure.
return chart;
}
/*
* Below is the initialization code as well as some helper functions
* to create a new bubble chart instance, load the data, and display it.
*/
var myBubbleChart = bubbleChart();
/*
* Function called once data is loaded from CSV.
* Calls bubble chart function to display inside #vis div.
*/
function display(error, data) {
if (error) {
console.log(error);
}
myBubbleChart('#vis', data);
}
/*
* Sets up the layout buttons to allow for toggling between view modes.
*/
function setupButtons() {
d3.select('#toolbar')
.selectAll('.button')
.on('click', function () {
// Remove active class from all buttons
d3.selectAll('.button').classed('active', false);
// Find the button just clicked
var button = d3.select(this);
// Set it as the active button
button.classed('active', true);
// Get the id of the button
var buttonId = button.attr('id');
// Toggle the bubble chart based on
// the currently clicked button.
myBubbleChart.toggleDisplay(buttonId);
});
}
/*
* Helper function to convert a number into a string
* and add commas to it to improve presentation.
*/
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
// Load the data.
d3.csv('condensed_overview.csv', display);
// setup the buttons.
setupButtons();
</script>
</body>