-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchord_with_comm_tally_data.html
653 lines (547 loc) · 19.9 KB
/
chord_with_comm_tally_data.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
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
#circle circle {
fill: none;
pointer-events: all;
}
path.chord {
stroke: #000;
stroke-width: .10px;
transition: opacity 0.3s;
}
#circle:hover path.fade {
opacity: 0;
}
</style>
<head>
<title>Call and Text Data Over Time</title>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/colorbrewer.v1.min.js"></script>
<table>
<tr><td>User:</td><td><div id="selector"></div></td><td><div id="zoomIn"></div></td><td><div id="zoomOut"></div></td></tr>
</table>
<form name="sort">
<input type="range" name="dateFilter" min="0" max="50" step="1" value="50">
</form>
<div id="filterDate"></div>
<script>
var comm = [];
//var date = "2009-06-16 15:00:25"; //not used any more
var remaining = 1;
var dateRange = [];
var timeScale = d3.scale.quantize();
var width = 1300,
height = 700,
innerRadius = Math.min(width, height) * .41,
outerRadius = innerRadius * 1.1;
var svg, students_g, text_g, ticks_g;
var filterLevel, filterDate;
var last_layout; //store layout between updates
var user;
//create the arc path data generator for the groups
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
//create the chord path data generator for the chords
var path = d3.svg.chord()
.radius(innerRadius);
// uncomment for simple set
/*
var YmdXParser = d3.time.format("%Y-%m-%d %X").parse;
var file = "../newdata/communication-tally-by-pair-full-small.csv";
*/
var YmdXParser = d3.time.format("%Y-%m-%d").parse;
var file = "../andrew/data/com-pairs.csv";
loadComm();
function loadComm() {
// d3.csv("../newdata/communication-tally-by-pair-full-small.csv", function(error, data) {
d3.csv(file, function(error, data) {
// console.log(data);
if(!--remaining) { setRange(data); }
})
};
function setRange(data) {
// get a list of all the dates, since all objects are the same just look at the first one
for(var key in data[0]) {
if(YmdXParser(key)) { dateRange.push(key); }
}
// The order of object keys is not guaranteed in JS, so we must sort to be absolutely sure.
dateRange.sort(function(a,b) {
return new Date(a) - new Date(b);
})
//console.log("dateRange:", dateRange);
// create our timeScale
timeScale.domain([0,dateRange.length - 1]).range(dateRange)
// set our slider to correct values
document.forms[0].dateFilter.max = dateRange.length - 1;
document.forms[0].dateFilter.value = dateRange.length - 1;
createVis();
// update visualization on release of slider
d3.selectAll("input[name=dateFilter]")
.on("mouseup", function () { filterComm(data); });
d3.selectAll("input[name=dateFilter]")
.on("change", function () { updateDate(); });
// Drop down selector to show choices for users
var userDropDown = d3.select("#selector")
.append("select")
.on("change", function() {
user = this.options[this.selectedIndex].value;
filterComm(data);
});
// Options for 1 to 80
var userOptions = userDropDown.selectAll("option")
.data(function() { var tempArray = [];
tempArray.push("all");
for(i=1;i<=80;i++) {
tempArray.push(i);
}
return tempArray;
})
.enter()
.append("option")
.text(function (d) { return d; })
.attr("value", function (d) { return d; });
// in case no dropDown event is trigged and they just leave it as default, will display "all" users
user = userDropDown.node().value;
// zoom chord graph out
var zoomOut = d3.select("#zoomOut")
.append("button")
.text("zoomOut")
.on("click",function() { // d3.select("#circle").transition().delay(250).attr("transform", "scale(0)");
d3.select("#circle").transition().delay(250).attr("transform", "translate(" + width * .90 + "," + height * .15 + ") scale(.25)");
});
// zoom chord graph in
var zoomIn = d3.select("#zoomIn")
.append("button")
.text("zoomIn")
.on("click",function() { d3.select("#circle").transition().delay(250).attr("transform", "scale(1)").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); });
// call updateDate() and filterComm() on load so we have something to look at
updateDate();
filterComm(data);
}
function updateDate() {
// Read our filter level from our slider
filterLevel = parseInt(document.forms[0].dateFilter.value);
// Get filterDate from filterLevel
filterDate = new Date(timeScale(filterLevel));
// Display the date selected
d3.select("#filterDate")
.text(filterDate);
}
// filter our data based on the slider
function filterComm(data) {
var key = timeScale(filterLevel);
// console.log(key);
// Display the date selected
d3.select("#filterDate")
.text(filterDate);
// console.log("User is: ", user);
comm = [];
for (var i = 0; i<data.length; i++) {
if(+data[i]["source"] == +user || +data[i]["target"] == +user || user == "all") {
var dataobject = data[i];
commObject = {};
// console.log(dataobject["source"] + " : " + dataobject["target"] + " -> " + dataobject[key]);
commObject["source"] = +dataobject["source"];
commObject["target"] = +dataobject["target"];
commObject["freq"] = +dataobject[key];
// console.log(dataobject);
comm.push(commObject);
}
};
// console.log(comm);
matrixmap(comm);
}
function matrixmap(comm) {
var matrix = [];
var users = [];
// console.log(comm);
/*get all the unique users (both senders & receivers)
because that is going to be the number of arrays in the
square matrix.*/
//first add all unique source IDs
for (var i = 0; i< comm.length; i++) {
if (comm[i]["freq"] != 0) {
var add = 1;
for (var u = 0; u < users.length; u++) {
if (comm[i]["source"] == users[u]) {
add = 0;
};
}
if (add == 1) {
users.push(+comm[i]["source"]);
}
}
}
//then add any unique Target IDs that weren't already added
for (var i = 0; i< comm.length; i++) {
if (comm[i]["freq"] != 0) {
var add = 1;
for (var u = 0; u < users.length; u++) {
if (comm[i]["target"] == users[u]) {
add = 0;
};
}
if (add == 1) {
users.push(comm[i]["target"]);
}
}
}
users.sort(function(a,b) {
return a - b;
})
// console.log(users);
//intialize the square matrix and put 0s in
//so the values can be incremented later.
matrix.length = users.length;
for (var i = 0; i< matrix.length; i++) {
matrix[i] = [];
matrix[i].length = matrix.length;
for (var j = 0; j<matrix.length; j++) {
matrix[i][j] = 0;
}
};
// console.log(matrix);
//populate the matrix with the frequency value
//for the source/user combination
for (var u = 0; u<users.length; u++) {
for (var c = 0; c<comm.length; c++) {
if (comm[c]["source"] == users[u]) {
for (var u2 = 0; u2<users.length; u2++) {
if (comm[c]["target"] == users[u2]) {
matrix[u][u2] = comm[c]["freq"];
}
}
}
}
};
// console.log(matrix);
updateVis(matrix, users);
}
function createVis() {
svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("id", "circle")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
svg.append("circle")
.attr("r", outerRadius);
}
function getDefaultLayout() {
return d3.layout.chord()
.padding(0.03)
.sortSubgroups(d3.descending)
.sortChords(d3.ascending);
}
// some ideas pulled from http://fleetinbeing.net/d3e/chord.html
// and http://stackoverflow.com/questions/21813723/change-and-transition-dataset-in-chord-diagram-with-d3
function updateVis(matrix, users) {
var layout = getDefaultLayout();
layout.matrix(matrix);
var fill = d3.scale.ordinal()
.domain(d3.range(users.length))
.range(colorbrewer.Paired[12]);
svg.selectAll("g.group").remove();
svg.selectAll("g.path").remove();
/* Create/update "group" elements */
var groupG = svg.selectAll("g.group")
.data(layout.groups(), function (d) {
return d.index;
//use a key function in case the
//groups are sorted differently between updates
});
groupG.exit()
.transition()
.duration(1500)
.attr("opacity", 0)
.remove(); //remove after transitions are complete
var newGroups = groupG.enter().append("g")
.attr("class", "group");
//the enter selection is stored in a variable so we can
//enter the <path>, <text>, and <title> elements as well
//Create the title tooltip for the new groups
newGroups.append("title");
//Update the (tooltip) title text based on the data
groupG.select("title")
.text(function(d, i) {
return parseInt(d.value)
+ " calls from "
+ "user " + users[i];
});
//create the arc paths and set the constant attributes
//(those based on the group index, not on the value)
newGroups.append("path")
.attr("id", function (d) {
return "group" + d.index;
//using d.index and not i to maintain consistency
//even if groups are sorted
})
.style("fill", function(d) { return fill(d.index); });
//update the paths to match the layout
groupG.select("path")
.transition()
.duration(1500)
.attr("opacity", 0.5) //optional, just to observe the transition
.attrTween("d", arcTween( last_layout ))
.transition().duration(100).attr("opacity", 1); //reset opacity
//create the group labels
newGroups.append("svg:text")
.attr("xlink:href", function (d) {
return "#group" + d.index;
})
.attr("dy", ".35em")
.attr("color", "#fff")
.text(function (d) {
if (users[d.index] == "0") {return "unknown user";}
else {return "user " + users[d.index];} });
//position group labels to match layout
groupG.select("text")
.transition()
.duration(1500)
.attr("transform", function(d) {
d.angle = (d.startAngle + d.endAngle) / 2;
//store the midpoint angle in the data object
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" +
" translate(" + (innerRadius + 30) + ")" +
(d.angle > Math.PI ? " rotate(180)" : " rotate(0)");
//include the rotate zero so that transforms can be interpolated
})
.attr("text-anchor", function (d) {
return d.angle > Math.PI ? "end" : "begin";
});
/* Create/update the chord paths */
var chordPaths = svg.selectAll("path.chord")
.data(layout.chords(), chordKey );
//specify a key function to match chords
//between updates
//create the new chord paths
var newChords = chordPaths.enter()
.append("path")
.attr("class", "chord");
// Add title tooltip for each new chord.
newChords.append("title");
// Update all chord title texts
chordPaths.select("title")
.text(function(d) {
if (users[d.target.index] !== users[d.source.index]) {
return [parseInt(d.source.value),
" calls from ",
"user ", users[d.source.index],
" to ",
"user ", users[d.target.index],
"\n",
parseInt(d.target.value),
" calls from ",
"user ", users[d.target.index],
" to ",
"user ", users[d.source.index]
].join("");
//joining an array of many strings is faster than
//repeated calls to the '+' operator,
//and makes for neater code!
}
else { //source and target are the same
return parseInt(d.source.value)
+ " calls to/from "
+ "user " + users[d.source.index];
}
});
//handle exiting paths:
chordPaths.exit().transition()
.duration(1500)
.attr("opacity", 0)
.remove();
//update the path shape
chordPaths.transition()
.duration(1500)
.attr("opacity", 0.5) //optional, just to observe the transition
.style("fill", function(d) { return fill(d.source.index); })
.attrTween("d", chordTween(last_layout))
.transition().duration(100).attr("opacity", 1); //reset opacity
//add the mouseover/fade out behaviour to the groups
//this is reset on every update, so it will use the latest
//chordPaths selection
groupG.on("mouseover", function(d) {
chordPaths.classed("fade", function (p) {
//returns true if *neither* the source or target of the chord
//matches the group that has been moused-over
return ((p.source.index != d.index) && (p.target.index != d.index));
});
});
//the "unfade" is handled with CSS :hover class on g#circle
//you could also do it using a mouseout event:
/*
g.on("mouseout", function() {
if (this == g.node() )
//only respond to mouseout of the entire circle
//not mouseout events for sub-components
chordPaths.classed("fade", false);
});
*/
last_layout = layout; //save for next update
}
/*
// Returns an event handler for fading a given chord group.
function fade(opacity) {
return function(g, i) {
svg.selectAll(".chord path")
.filter(function(d) { return d.source.index != i && d.target.index != i; })
.transition()
.style("opacity", opacity);
};
}
*/
function arcTween(oldLayout) {
//this function will be called once per update cycle
//Create a key:value version of the old layout's groups array
//so we can easily find the matching group
//even if the group index values don't match the array index
//(because of sorting)
var oldGroups = {};
if (oldLayout) {
oldLayout.groups().forEach( function(groupData) {
oldGroups[ groupData.index ] = groupData;
});
}
return function (d, i) {
var tween;
var old = oldGroups[d.index];
if (old) { //there's a matching old group
tween = d3.interpolate(old, d);
}
else {
//create a zero-width arc object
var emptyArc = {startAngle:d.startAngle,
endAngle:d.startAngle};
tween = d3.interpolate(emptyArc, d);
}
return function (t) {
return arc( tween(t) );
};
};
}
function chordKey(data) {
return (data.source.index < data.target.index) ?
data.source.index + "-" + data.target.index:
data.target.index + "-" + data.source.index;
//create a key that will represent the relationship
//between these two groups *regardless*
//of which group is called 'source' and which 'target'
}
function chordTween(oldLayout) {
//this function will be called once per update cycle
//Create a key:value version of the old layout's chords array
//so we can easily find the matching chord
//(which may not have a matching index)
var oldChords = {};
if (oldLayout) {
oldLayout.chords().forEach( function(chordData) {
oldChords[ chordKey(chordData) ] = chordData;
});
}
return function (d, i) {
//this function will be called for each active chord
var tween;
var old = oldChords[ chordKey(d) ];
if (old) {
//old is not undefined, i.e.
//there is a matching old chord value
//check whether source and target have been switched:
if (d.source.index != old.source.index ){
//swap source and target to match the new data
old = {
source: old.target,
target: old.source
};
}
tween = d3.interpolate(old, d);
}
else {
//create a zero-width chord object
var emptyChord = {
source: { startAngle: d.source.startAngle,
endAngle: d.source.startAngle},
target: { startAngle: d.target.startAngle,
endAngle: d.target.startAngle}
};
tween = d3.interpolate( emptyChord, d );
}
return function (t) {
//this function calculates the intermediary shapes
return path(tween(t));
};
};
}
/*
function chordTween(oldLayout) {
//this function will be called once per update cycle
//Create a key:value version of the old layout's chords array
//so we can easily find the matching chord
//(which may not have a matching index)
var oldChords = {};
if (oldLayout) {
oldLayout.chords().forEach( function(chordData) {
oldChords[ chordKey(chordData) ] = chordData;
});
}
return function (d, i) {
//this function will be called for each active chord
var tween;
var old = oldChords[ chordKey(d) ];
if (old) {
//old is not undefined, i.e.
//there is a matching old chord value
//check whether source and target have been switched:
if (d.source.index != old.source.index ){
//swap source and target to match the new data
old = {
source: old.target,
target: old.source
};
}
tween = d3.interpolate(old, d);
}
else {
//create a zero-width chord object
if (oldLayout) {
var oldGroups = oldLayout.groups().filter(function(group) {
return ( (group.index == d.source.index) ||
(group.index == d.target.index) )
});
old = {source:oldGroups[0],
target:oldGroups[1] || oldGroups[0] };
//the OR in target is in case source and target are equal
//in the data, in which case only one group will pass the
//filter function
if (d.source.index != old.source.index ){
//swap source and target to match the new data
old = {
source: old.target,
target: old.source
};
}
}
else old = d;
var emptyChord = {
source: { startAngle: old.source.startAngle,
endAngle: old.source.startAngle},
target: { startAngle: old.target.startAngle,
endAngle: old.target.startAngle}
};
tween = d3.interpolate( emptyChord, d );
}
return function (t) {
//this function calculates the intermediary shapes
return path(tween(t));
};
};
}
*/
</script>