-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenergy-sankey.js
409 lines (360 loc) · 12.2 KB
/
energy-sankey.js
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
var slideYear = 2010,
indexYear = 1949,
endYear = 2040;
isSliding = false,
countryGreyBlue = "#b6c5d0",
currentWidth = $(".sankey-container").width();
if (currentWidth < 550) {
currentWidth = 550
};
if (currentWidth > 978) {
currentWidth = 978
};
var currentHeight = window.innerHeight * .8;
var margin = {
top: 5,
right: 5,
bottom: 5,
left: 5
},
width = currentWidth - margin.left - margin.right,
height = currentHeight - margin.top - margin.bottom;
var formatNumber = d3.format(",.2f%"), // two decimal places
format = function (d) {
return formatNumber(d) + " " + units;
},
color = d3.scale.category20c();
// append the svg canvas to the page
var svg = d3.select("#chart").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 + ")");
// Set the sankey diagram properties
var sankey = d3.sankey()
.nodeWidth(25)
.nodePadding(8)
.size([width, height]);
var path = sankey.link();
var graph, data, link, node, sliderEvent;
var energyValues = [];
var sliderDragVisible = true;
var play = null;
// load the data with d3.csv
d3.csv("energy-sankey-data.csv", function (data) {
graph = {
"nodes": [],
"links": []
};
data.forEach(function (d, i) {
var item = {
source: d.source,
target: d.target,
values: []
};
for (var j = indexYear; j <= endYear; j++) {
item.values.push(d[j.toString()]);
}
energyValues.push(item);
graph.nodes.push({
"name": d.source
});
graph.nodes.push({
"name": d.target
});
graph.links.push({
source: energyValues[i].source,
target: energyValues[i].target,
value: energyValues[i].values[slideYear - indexYear]
});
});
// this function returns unique nodes
graph.nodes = d3.keys(d3.nest()
.key(function (d) { return d.name; })
.map(graph.nodes));
//it appears d3 with force layout wants a numeric source and target
//so loop through each link replacing the text with its index from node
graph.links.forEach(function (d, i) {
graph.links[i].source = graph.nodes.indexOf(graph.links[i].source);
graph.links[i].target = graph.nodes.indexOf(graph.links[i].target);
energyValues[i].source = graph.links[i].source;
energyValues[i].target = graph.links[i].target;
});
//now loop through each nodes to make nodes an array of objects rather than an array of strings
graph.nodes.forEach(function (d, i) {
graph.nodes[i] = { "name": d };
});
// construct sankey
sankey
.nodes(graph.nodes)
.links(graph.links)
.layout();
// add in the links
link = svg.append("g").selectAll(".link")
.data(graph.links)
.enter().append("path")
.attr("class", "link")
.attr("id",
function (d, i) {
d.id = i;
return "link-" + i;
})
.attr("d", path)
.style("stroke", function (d) { return d.target.color = color(d.target.name.replace(/ .*/, "")); })
.style("stroke-width", function (d) { return Math.max(1, d.dy); })
.sort(function (a, b) { return b.dy - a.dy; })
.style("visibility",
function () {
if (this.__data__.value == 0) {
return "hidden";
} else {
return "visible";
}
});
// add in the nodes
node = svg.append("g").selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; })
.style("visibility",
function () {
if (this.__data__.value == 0) {
return "hidden";
} else {
return "visible";
}
})
.on("click", highlight_node_links)
.on("mouseout",onNodeMouseout)
.call(d3.behavior.drag()
.origin(function (d) { return d; })
.on("dragstart", function () { this.parentNode.appendChild(this); })
.on("drag", dragmove));
// add the rectangles for the nodes
node.append("rect")
.attr("height", function (d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.attr("class", function (d) { return d.name; })
.attr("class", function (d) { return d.name; })
.style("fill", function (d) { return d.color = color(d.name.replace(/ .*/, "")); })
.style("stroke", function (d) { return d3.rgb(d.color).darker(2); })
.style("stroke-width", "0px");
// add in the title for the nodes
node.append("text")
.attr("x", -2)
.attr("y", function (d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text( function (d) { return d.name; })
.style("font-size", function () {
var textSize = 0.01 * this.__data__.value;
if (textSize > 13) {
return "13px";
} else if (textSize < 10) {
return "10px";
} else {
return textSize.toString() + "px";
}
})
.filter(function (d) { return d.x < width / 2; })
.attr("x", 2 + sankey.nodeWidth())
.attr("text-anchor", "start");
function getValue(passedObj) {
return passedObj.__data__.value;
}
// update function
function updateData(index) {
currentWidth = $(".sankey-container").width();
if (currentWidth < 550) { currentWidth = 550 };
if (currentWidth > 978) { currentWidth = 978 };
width = currentWidth;
$("svg").width(currentWidth);
var newLinks = [];
energyValues.forEach(function (p, i) {
newLinks.push({
source: p.source,
target: p.target,
value: p.values[index]
});
});
graph.links = newLinks;
sankey
.nodes(graph.nodes)
.links(graph.links)
.size([width, height])
.layout();
d3.selectAll("rect").style("stroke-width", "20px");
d3.selectAll(".link")
.data(graph.links)
.attr("d", path)
.attr("id", function (d, i) {
d.id = i;
return "link-" + i;
})
.style("stroke", function (d) {
return d.target.color = color(d.target.name.replace(/ .*/, ""));
})
.style("stroke-width", function (d) {
return Math.max(1, d.dy);
})
.sort(function (a, b) {
return b.dy - a.dy;
});
d3.selectAll(".node").attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
d3.selectAll("rect")
.attr("height", function (d) {
return d.dy;
}).style("stroke-width", "0px");
d3.selectAll("text")
.attr("y", function (d) {
return d.dy / 2;
})
.style("font-size", function () {
var textSize = 0.01 * this.__data__.value;
if (textSize > 13) {
return "13px";
} else if (textSize < 10) {
return "10px";
} else {
return textSize.toString() + "px";
}
});
d3.selectAll("g.node")
.style("visibility", function () {
if (this.__data__.value < 0.0009) {
return "hidden";
} else {
return "visible";
}
});
d3.selectAll("path.link")
.style("visibility", function () {
if (this.__data__.value < 0.0009) {
return "hidden";
} else {
return "visible";
}
});
}
$(document).mouseleave(
function (event) {
$(".sankey-container").trigger("mouseup");
isSliding = false;
}
);
// link slider to update function
$(".sankey-slider").bind("slider:changed", function (event, data) {
if (!isSliding) {
$(".sankey-container").one("mouseup", function () {
isSliding = false;
});
isSliding = true;
}
slideYear = data.value;
d3.select("#year").text(slideYear);
updateData(parseInt(slideYear - indexYear));
});
// auto-advance year when play button is selected. currently
$("#btnStartSlide").on("click", function startSlide() {
if (play == null){
var year = indexYear;
play = setInterval( function() {
if (year < endYear + 1) {
if (!isSliding) {
isSliding = true;
}
slideYear = year;
$(".sankey-slider").val(slideYear);
//console.log($(".sankey-slider").val());
d3.select("#year").text(slideYear);
updateData(parseInt(slideYear - indexYear));
year += 1;
} else {
clearInterval(play);
play = null;
}
}, 300);
}
});
$("#btnStopSlide").on("click", function stopSlide() {
clearInterval(play);
play = null;
});
// highlight a node on hover
function highlight_node_links(node, i) {
if (isSliding){
return;
}
var remainingNodes = [],
nextNodes = [];
var stroke_opacity = 0;
if (d3.select(this).attr("data-clicked") == "1") {
d3.select(this).attr("data-clicked", "0");
stroke_opacity = 0.2;
} else {
d3.select(this).attr("data-clicked", "1");
stroke_opacity = 0.65;
}
var traverse = [{
linkType: "sourceLinks",
nodeType: "target"
}, {
linkType: "targetLinks",
nodeType: "source"
}];
traverse.forEach(function (step) {
node[step.linkType].forEach(function (link) {
remainingNodes.push(link[step.nodeType]);
highlight_link(link.id, stroke_opacity);
});
while (remainingNodes.length) {
nextNodes = [];
remainingNodes.forEach(function (node) {
node[step.linkType].forEach(function (link) {
nextNodes.push(link[step.nodeType]);
highlight_link(link.id, stroke_opacity);
});
});
remainingNodes = nextNodes;
}
});
// this section here controls the tooltip
var eX = this.__data__.x;
var eY = this.__data__.y + 130;
if( eX < width / 2 ){
eX = 110;
} else{
eX = width - 400;
if ( eY > (height+100)*0.9 ){ eY = (height+100)*0.9 }
};
d3.select(".hover-tooltip-sankey").transition().duration(50).delay(50)
.style("top",eY+"px").style("left",eX+"px")
.style("background-color","rgba(255,255,255,.9)")
.style("display","block");
d3.select(".hover-value").text((this.__data__.value).toFixed(0) + " Trillion Btu")
.transition().duration(50).delay(50).style("background-color","rgba(255,255,255,.9)");
}
// highlight link on hover
function highlight_link(id, opacity) {
d3.select("#link-" + id).style("stroke-opacity", opacity);
}
function onNodeMouseout(){
d3.select(".hover-tooltip-sankey")
.transition().duration(50).delay(50).style("background-color","rgba(255,255,255,0)").style("display","none");
d3.select(".hover-value").transition().duration(50).delay(50).style("background-color","rgba(255,255,255,0)");
}
function dragmove(d) {
d3.select(this).attr("transform",
"translate(" + (
d.x = Math.max(0, Math.min(width - d.dx, d3.event.x))
) + "," + (
d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))
) + ")");
sankey.relayout();
link.attr("d", path);
}
});