-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
464 lines (394 loc) · 14.3 KB
/
index.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
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.link {
fill: none;
stroke: #555;
stroke-opacity: 0.4;
stroke-width: 1px;
}
text {
font-family: "Arial Black", Gadget, sans-serif;
fill: black;
font-weight: bold;
font-size: 12px
}
.xAxis .tick text {
fill: black;
}
.grid .tick line {
stroke: grey;
stroke-dasharray: 5, 10;
opacity: 0.7;
}
.grid path {
stroke-width: 0;
}
.node {
cursor: pointer;
}
.node circle {
fill: #999;
}
.node--internal circle {
fill: #555;
}
.node--internal text {
font-size: 12px;
text-shadow: 0 2px 0 #fff, 0 -2px 0 #fff, 2px 0 0 #fff, -2px 0 0 #fff;
}
.node--leaf text {
fill: #000000;
}
.node--collapsed text {
fill: #000;
}
.node--collapsed circle {
fill: #555;
}
.ballG text {
fill: white;
}
.shadow {
-webkit-filter: drop-shadow(-1.5px -1.5px 1.5px #000);
filter: drop-shadow(-1.5px -1.5px 1.5px #000);
}
svg {
border: black solid 1px;
}
div.tooltip {
position: absolute;
text-align: center;
padding: 4px;
font-size: 12px;
font-family: "Arial Black", Gadget, sans-serif;
font-weight: bold;
background: #ebebeb;
border: solid 1px black;
border-radius: 8px;
pointer-events: none;
}
</style>
<body style="display: flex; flex-direction: column;">
<select id="mySelect" onchange="changeFile()">
<option value="animal2002.json">Animalia Corrected
<option value="animal2000.json">Animalia Error
<option selected="selected" value="sciences.json">Sciences Multiple Roots
</select>
<svg width="1000" height="500"></svg>
<div class="tooltip"></div>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="lodash.js"></script>
<script>
var transition = d3.transition().duration(500)
// main svg - get the initial size and append a g element to svg
var svg = d3.select("svg"),
g = svg.append("g").attr("transform", "translate(20,20)"), // move right 20px.
tooltip = d3.select(".tooltip")
.style("opacity", 0);
// define the zoomListener which calls the zoom function on the "zoom" event
var zoomListener = d3.zoom().on("zoom", zoom);
svg.call(zoomListener);
var xScale = d3.scaleLinear()
.domain([0, 5]) // the values
.range([0, 500]);
var xAxis = d3.axisTop()
.scale(xScale)
.ticks(5);
// Setting up a way to handle the data
var tree = d3.cluster() // This D3 API method setup the Dendrogram elements position.
.separation(function(a, b) { return a.parent == b.parent ? 3 : 4; }); // define separation ratio between siblings
var stratify = d3.stratify() // This D3 API method gives cvs file flat data array dimensions.
.id(function(d) { return d.target; })
.parentId(function (d) { return d.source; });
let myData;
let root;
changeFile();
function zoom() {
g.attr("transform", d3.event.transform);
}
function changeFile() {
var selectedFile = document.getElementById("mySelect").value;
svg.select("g").remove();
g = svg.append("g").attr("transform", "translate(20,20)");
g.insert("g").attr("class", "grid");
// g.insert("g").attr("class","xAxis");
tooltip = d3.select(".tooltip")
.style("background-color", "")
.style("color", "")
.style("border-color", "")
.style("opacity", 0);
d3.json(selectedFile, function (error, treeData) {
if (error) throw error;
// add link weight when duplicated
var formatedData = [];
treeData.data.forEach(d => {
let index = formatedData.findIndex(f => f.target === d.target && f.source === d.source)
if(index < 0) {
formatedData.push(d);
} else {
formatedData[index].wieght += d.weight;
}
})
myData = addRootElements(formatedData);
try {
root = stratify(myData);
// collpsed all nodes
root.children.forEach(d => d.children.forEach(collapse))
maxWeight =d3.max(root.leaves(), function(d) {
return d.data.weight;
})
// set axis dimension
xScale.domain([0, maxWeight])
xAxis.scale(xScale)
update();
} catch (error) {
//return elements with multiple parents
var grouped = _.mapValues(_.groupBy(formatedData, 'target'), function(d) {return d.length;});
_.keysIn(grouped).forEach(k => {
if(grouped[k]> 1) {
console.log(k, grouped[k])
}
})
tooltip.style("background-color", "red")
.style("color", "white")
.style("border-color", "red")
.style("opacity", 1)
.style("top", `${+svg.attr("height") / 2}px`)
.style("left", `${(+svg.attr("width") / 2) -140}px`)
.html(`An error occured while rendering the graph:<br>${error}`);
}
});
}
function update() {
// update tree size
var height = (root.leaves().length + 1) * 50;
var width = (root.depth + root.height) * 200;
tree.size([height, width]);
// update axis
maxWeight =d3.max(root.descendants().filter(d => !d.children && !d._children), function(d) {
return d.data.weight;
})
xScale.domain([0, maxWeight])
xAxis.scale(xScale)
tree(root); // d3.cluster()
root.descendants().forEach(d => {
d.y = d.x;
d.x = (d.depth - 1) / (d.depth + d.height - 1) * width;
});
// Draw every datum a line connecting to its parent.
var link = g.selectAll(".link")
.data(root.descendants().slice(1).filter(d => !d.parent.data.isFakeNode && !d.parent.isCollapsedNode), function (d) {
return d.id;
}); // remove links from fakeRootNode
//remove old links
link.exit().remove()
// update remaining link
link.attr("d", function (d) {
return "M" + d.x + "," + d.y
+ "C" + (d.parent.x + 100) + "," + d.y
+ " " + (d.parent.x + 100) + "," + d.parent.y
+ " " + d.parent.x + "," + d.parent.y;
});
// add new one
link.enter().append("path")
.attr("class", "link")
.attr("d", function (d) {
return "M" + d.x + "," + d.y
+ "C" + (d.parent.x + 100) + "," + d.y
+ " " + (d.parent.x + 100) + "," + d.parent.y
+ " " + d.parent.x + "," + d.parent.y;
});
// Setup position for every datum; Applying different css classes to parents and leafs.
var node = g.selectAll(".node")
.data(root.descendants().filter(d => {
return !d.data.isFakeNode; // remove fake node (ie: fakeRoot and fake children when collapsed)
}), function(d) {
return d.id;
});
// remove old nodes
node.exit().remove()
//udpate remaining nodes
node.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
var nodeLeafG = node.filter(function(d) {
return !d.children && !d._children;
}).selectAll("g");
nodeLeafG.select("rect")
.attr("width", function (d) { return xScale(d.data.weight); });
nodeLeafG.select("text")
.attr("width", function (d) { return xScale(d.data.weight) - 8; })
.text(function(d) {
return d.id;
});
// .call(dotme);
// add new nodes
var nodeEnter = node.enter().append("g")
.attr("class", function (d) { return "node" + ((d.children || d._children) ? " node--internal" : " node--leaf") + (d._children ? ' node--collapsed' : ''); })
.on("click", click)
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
})
nodeEnter.append("circle")
.attr("r", 4);
var nodeInternal = nodeEnter.filter(function(d) {
return (d.children || d._children);
});
nodeInternal.append("text")
.style("text-anchor", "start")
.text(function(d) {
return d.id;
})
.attr("y", -10);
// Setup G for every leaf datum. (rectangle)
var leafNodeGEnter = nodeEnter.filter(function(d) {
return !d.children && !d._children;
}).append("g")
.attr("class", "node--leaf-g")
.attr("transform", "translate(" + 8 + "," + 0 + ")"); // move rectangle to be centered to the node
leafNodeGEnter.append("rect")
.attr("class", "")
.style("fill", function (d) { return "#555"; })
.attr("width", 2)
.attr("height", 10)
.attr("rx", 2)
.attr("ry", 2)
.transition(transition)
.attr("width", function (d) { return xScale(d.data.weight); });
leafNodeGEnter.append("text")
.style("text-anchor", "start")
.text(function(d) {
return d.id;
})
.attr("dy", -5)
.attr("x", 8)
.attr("width", function (d) { return xScale(d.data.weight) - 8; });
// Attach the xAxis a the top of the document
// g.select(".xAxis").attr("transform", "translate(" + (7 + width ) + "," + 0 + ")")
// .call(xAxis);
g.select(".grid").attr("transform", "translate(" + (7 + width) + "," + height + ")")
.call(d3.axisBottom()
.scale(xScale)
.ticks(5)
.tickSize(-height, 0, 0)
.tickFormat("")
);
// Emphasize the y-axis baseline.
svg.select(".grid").select("line")
.style("stroke-dasharray", "20,1")
.style("stroke", "black");
//// Animation functions for mouse on and off events.
d3.selectAll(".node--leaf-g")
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut);
d3.selectAll(".node--internal")
.on("mouseover", handleMouseOverInternalNode)
.on("mouseout", handleMouseOutInternalNode);
function handleMouseOver(d) {
var leafG = d3.select(this);
leafG.select("rect")
.attr("stroke","#4D4D4D")
.attr("stroke-width","2");
let textSize = leafG.select("text").node().getComputedTextLength(); //get text length
tooltip.style("opacity", 1);
tooltip.html(`${d.data.weight.toFixed(0)} documents`)
.style("left", d3.event.pageX + "px")
.style("top", (d3.event.pageY - 28) + "px");
}
function handleMouseOut() {
var leafG = d3.select(this);
leafG.select("rect")
.attr("stroke-width","0");
tooltip.style("opacity", 0);
}
}
function handleMouseOverInternalNode(d) {
var nodeG = d3.select(this);
var text = nodeG.select("text");
tooltip.style("opacity", 1);
tooltip.html(`${d.data.weight.toFixed(0)} documents`)
.style("left", (d3.event.pageX - text.node().getComputedTextLength() *0.5) + "px")
.style("top", (d3.event.pageY - 28) + "px");
nodeG.select("circle")
.attr("r", 8)
}
function handleMouseOutInternalNode(d) {
tooltip.style("opacity", 0);
d3.select(this).select("circle")
.attr("r", 4)
}
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
function expand(d) {
if (d._children) {
d.children = d._children;
d._children = null;
}
}
function click(d) {
if(d.children) {
collapse(d)
} else {
expand(d)
}
update();
centerNode(d)
}
function centerNode(source) {
scale = d3.zoomTransform(this).k;
x = -source.x;
y = -source.y;
x = x * scale + d3.select("svg").attr("width") / 2;
y = y * scale + d3.select("svg").attr("height") / 2;
svg.call(d3.zoom().transform, d3.zoomIdentity.translate(x, y));
g.transition(transition).attr('transform', 'translate(' + x + ',' + y + ')');
}
function addRootElements(data) {
newData = [];
elementsDone = [];
parentsAdded = [];
for (let elem of data) {
if (elementsDone.indexOf(elem.target) < 0) {
let parentExist = false;
elementsDone.push(elem.target);
for (let comparedElem of data) {
if (comparedElem.target == elem.source) {
parentExist = true;
}
}
if (!parentExist) {
if (parentsAdded.indexOf(elem.source) < 0) {
newData.push({
source: 'fakeRoot',
target: elem.source,
weight: 0
});
parentsAdded.push(elem.source);
}
}
}
}
newData.push({
source: '',
target: 'fakeRoot',
weight: 0,
isFakeNode: true
});
newData.push.apply(newData, data);
return newData;
}
function row(d) {
return {
id: d.id,
value: +d.data.weight,
color: `#454545`
};
}
</script>