dendrogram.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /* based on https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5ecd */
  2. Shiny.addCustomMessageHandler("dendrogram_values", function(message) {
  3. var dataset = message[0];
  4. var bardata = message[1];
  5. var radardata = message[2];
  6. var k = 0;
  7. // Set the dimensions and margins of the diagram
  8. var margin = {top: 20, right: 90, bottom: 30, left: 90},
  9. width = window.innerWidth - margin.left - margin.right,
  10. height = window.innerHeight - margin.top - margin.bottom;
  11. // scales for barchart
  12. var xScale = d3.scaleBand()
  13. .domain(d3.range(bardata[0].value.length))
  14. .range([0, width * 0.55])
  15. .paddingInner(0.5);
  16. var yScale = d3.scaleLinear()
  17. .domain([0, d3.max(bardata[0].value)])
  18. .range([0, 100]);
  19. // We can freely modify this scale
  20. var yScaleb = d3.scaleLinear()
  21. .domain([0, d3.max(bardata[0].value)])
  22. .range([0, 100]);
  23. //Radar chart configuration
  24. var radarChartOptions = {
  25. w: width * 0.1,
  26. h: height * 0.1,
  27. labelFactor: 1.25,
  28. opacityArea: 0.20,
  29. strokeWidth: 2,
  30. };
  31. var maxValue = d3.max(radardata[0].value, function(d) {
  32. return d.value;
  33. });
  34. var allAxis = (radardata[0].value.map(function(d) {
  35. return d.axis;
  36. }));
  37. var total = allAxis.length,
  38. radius = Math.min(radarChartOptions.w/4, radarChartOptions.h/4),
  39. angleSlice = Math.PI * 2 / total;
  40. //Scale for the radius
  41. var rScale = d3.scaleLinear()
  42. .domain([0, maxValue])
  43. .range([0, radius]);
  44. //End radar chart configuration
  45. //Create an area to display information about glyph
  46. d3.select("body")
  47. .append("div")
  48. .attr("id", "tooltip_area")
  49. .style("position", "absolute")
  50. .style("left", width/20 + "px")
  51. .style("top", height/10 + "px")
  52. .style("z-index", "10")
  53. .style("visibility", "hidden")
  54. .style("color", "white")
  55. .style("padding", "8px")
  56. .style("background-color", "rgba(0, 0, 0, 0.75)")
  57. .style("border-radius", "6px")
  58. .style("font", "20px sans-serif")
  59. .text("tooltip");
  60. // append the svg object to the area reserved for the dendrogram
  61. // appends a 'group' element to 'svg'
  62. // moves the 'group' element to the top left margin
  63. var dendrogram_plot = d3.select("#dendrogram_area").append("svg")
  64. .attr("width", width + margin.right + margin.left)
  65. .attr("height", height + margin.top + margin.bottom)
  66. .append("g")
  67. .attr("transform", "translate("
  68. + margin.left + "," + margin.top + ")");
  69. var i = 0,
  70. duration = 750,
  71. root;
  72. // declares a tree layout and assigns the size
  73. var dendrogram = d3.cluster().size([height, width * 0.4]);
  74. // Assigns parent, children, height, depth
  75. root = d3.hierarchy(dataset, function(d) { return d.children; });
  76. root.x0 = height / 2;
  77. root.y0 = 0;
  78. // Collapse after the second level
  79. root.children.forEach(collapse);
  80. update(root);
  81. //By default show bars and radars only on last level
  82. toggleBars(root);
  83. toggleRadars(root);
  84. // Collapse the node and all it's children
  85. function collapse(d) {
  86. if(d.children) {
  87. d._children = d.children;
  88. d._children.forEach(collapse);
  89. d.children = null;
  90. }
  91. }
  92. function update(source) {
  93. // Assigns the x and y position for the nodes
  94. var dataset = dendrogram(root);
  95. // Compute the new tree layout.
  96. var nodes = dataset.descendants(),
  97. links = dataset.descendants().slice(1);
  98. // ****************** Nodes section ***************************
  99. //nodes.eachAfter(function(d) { d.y = d.depth * 180; });
  100. // Update the nodes...
  101. var node = dendrogram_plot.selectAll('g.node')
  102. .data(nodes, function(d) {return d.id || (d.id = ++i); });
  103. // Enter any new modes at the parent's previous position.
  104. var nodeEnter = node.enter().append('g')
  105. .attr('class', 'node')
  106. .attr('id', function(d) {
  107. return "node-" + (d.id -1);
  108. })
  109. .attr("transform", function(d) {
  110. return "translate(" + source.y0 + "," + source.x0 + ")";
  111. })
  112. .on('click', click)
  113. .on('wheel', reScaleBars)
  114. .on('auxclick', resetBars);
  115. // Add Circle for the nodes
  116. nodeEnter.append('circle')
  117. .attr('class', 'node')
  118. .attr('r', 1e-6)
  119. .style("fill", function(d) {
  120. return d._children ? "lightsteelblue" : "#fff";
  121. });
  122. // Add labels for the nodes
  123. nodeEnter.append('text')
  124. .attr("dy", ".35em")
  125. .attr("x", function(d) {
  126. //return d.children || d._children ? -13 : 13;
  127. return -13;
  128. })
  129. .attr("text-anchor", function(d) {
  130. //return d.children || d._children ? "end" : "start";
  131. return "end";
  132. })
  133. .text(function(d) { return d.data.name; });
  134. // Add barcharts to nodes
  135. nodeEnter
  136. .selectAll("rect")
  137. .data(function(d) {
  138. if (d.data.name == "Brasil") {
  139. return bardata[0].value;
  140. }
  141. for (var i = 1; i < bardata.length; i++) {
  142. if (d.data.name == bardata[i].name[1]) {
  143. if (d.ancestors()[1].data.name == bardata[i].name[0]) {
  144. return bardata[i].value;
  145. }
  146. }
  147. }
  148. return 0;
  149. })
  150. .enter()
  151. .append("rect")
  152. .classed("bars", true)
  153. .attr("x", function(d, i) {
  154. return 13 + xScale(i);
  155. })
  156. .attr("y", function(d) {
  157. return 13 -yScale(d);
  158. })
  159. .attr("width", xScale.bandwidth())
  160. .attr("height", function(d) {
  161. return yScale(d);
  162. })
  163. .attr("fill", "blue");
  164. // Add radar charts to nodes
  165. radarBuild = nodeEnter
  166. .append("svg")
  167. .attr("width", width)
  168. .attr("height", height/8)
  169. .attr("transform", "translate(" + (0) + "," + (-50) + ")")
  170. .attr("class", "radar")
  171. .append("g")
  172. .attr("transform", "translate(" + (50 + xScale(364)) + "," + (50) + ")")
  173. .on('mouseover', showToolTip)
  174. .on('mouseout', hideToolTip);
  175. var axisGrid = radarBuild.append("g").attr("class", "axisWrapper");
  176. //Create the straight lines radiating outward from the center
  177. /*var axis = axisGrid.selectAll(".axis")
  178. .data(allAxis)
  179. .enter()
  180. .append("g")
  181. .attr("class", "axis");*/
  182. //Append the lines
  183. /*axis.append("line")
  184. .attr("x1", 0)
  185. .attr("y1", 0)
  186. .attr("x2", function(d, i) {
  187. return rScale(maxValue) * Math.cos(angleSlice*i - Math.PI/2);
  188. })
  189. .attr("y2", function(d, i) {
  190. return rScale(maxValue) * Math.sin(angleSlice*i - Math.PI/2);
  191. })
  192. .attr("class", "radarLine")
  193. .style("stroke", "#CDCDCD")
  194. .style("stroke-width", "2px")
  195. .style("stroke-dasharray", "5,5");*/
  196. //Append the labels at each axis
  197. /*axis.append("text")
  198. .attr("class", "radarLegend")
  199. .style("font-size", "8px")
  200. .attr("text-anchor", "middle")
  201. .attr("dy", "0.35em")
  202. .attr("x", function(d, i) {
  203. return rScale(maxValue*1.1 * radarChartOptions.labelFactor) * Math.cos(angleSlice*i - Math.PI/2);
  204. })
  205. .attr("y", function(d, i) {
  206. return rScale(maxValue*1.1 * radarChartOptions.labelFactor) * Math.sin(angleSlice*i - Math.PI/2);
  207. })
  208. .text(function(d){return d;});*/
  209. //The radial line function
  210. var radarLine = d3.lineRadial()
  211. .curve(d3.curveLinearClosed)
  212. .angle(function(d, i) {return i * angleSlice; })
  213. .radius(function(d) {
  214. return rScale(d.value);
  215. });
  216. //Create a wrapper for the blobs
  217. var blobWrapper = radarBuild.selectAll(".radarWrapper")
  218. .data(function(d) {
  219. if (d.data.name == "Brasil") {
  220. return [radardata[0].value];
  221. }
  222. for (var i = 1; i < radardata.length; i++) {
  223. if (d.data.name == radardata[i].name[1]) {
  224. if (d.ancestors()[1].data.name == radardata[i].name[0]) {
  225. return [radardata[i].value];
  226. }
  227. }
  228. }
  229. return 0;
  230. })
  231. .enter()
  232. .append("g")
  233. .attr("class", "radarWrapper");
  234. //Append the backgrounds
  235. blobWrapper
  236. .append("path")
  237. .attr("d", function() {
  238. maxValue = d3.max(d3.select(this).data()[0], function(v) {
  239. return v.value;
  240. });
  241. rScale
  242. .domain([0, maxValue]);
  243. return radarLine(d3.select(this).data()[0]);
  244. })
  245. .attr("class", "radarArea")
  246. .style("fill", "#EDC951")
  247. .style("fill-opacity", radarChartOptions.opacityArea);
  248. //Create the outlines
  249. blobWrapper.append("path")
  250. .attr("class", "radarStroke")
  251. .attr("d", function() {
  252. maxValue = d3.max(d3.select(this).data()[0], function(v) {
  253. return v.value;
  254. });
  255. rScale
  256. .domain([0, maxValue]);
  257. return radarLine(d3.select(this).data()[0]);
  258. })
  259. .style("stroke-width", radarChartOptions.strokeWidth + "px")
  260. .style("stroke", "black")
  261. .style("fill", "none");
  262. // UPDATE
  263. var nodeUpdate = nodeEnter.merge(node);
  264. // Transition to the proper position for the node
  265. nodeUpdate.transition()
  266. .duration(duration)
  267. .attr("transform", function(d) {
  268. return "translate(" + d.y + "," + d.x + ")";
  269. });
  270. // Update the node attributes and style
  271. nodeUpdate.select('circle.node')
  272. .attr('r', 10)
  273. .style("fill", function(d) {
  274. return d._children ? "lightsteelblue" : "#fff";
  275. })
  276. .attr('cursor', 'pointer');
  277. // Remove any exiting nodes
  278. var nodeExit = node.exit().transition()
  279. .duration(duration)
  280. .attr("transform", function(d) {
  281. return "translate(" + source.y + "," + source.x + ")";
  282. })
  283. .remove();
  284. // On exit reduce the node circles size to 0
  285. nodeExit.select('circle')
  286. .attr('r', 1e-6);
  287. // On exit reduce the opacity of text labels
  288. nodeExit.select('text')
  289. .style('fill-opacity', 1e-6);
  290. // ****************** links section ***************************
  291. // Update the links...
  292. var link = dendrogram_plot.selectAll('path.link')
  293. .data(links, function(d) { return d.id; });
  294. // Enter any new links at the parent's previous position.
  295. var linkEnter = link.enter().insert('path', "g")
  296. .attr("class", "link")
  297. .attr('d', function(d){
  298. var o = {x: source.x0, y: source.y0};
  299. return diagonal(o, o);
  300. });
  301. // UPDATE
  302. var linkUpdate = linkEnter.merge(link);
  303. // Transition back to the parent element position
  304. linkUpdate.transition()
  305. .duration(duration)
  306. .attr('d', function(d){ return diagonal(d, d.parent); });
  307. // Remove any exiting links
  308. var linkExit = link.exit().transition()
  309. .duration(duration)
  310. .attr('d', function(d) {
  311. var o = {x: source.x, y: source.y};
  312. return diagonal(o, o);
  313. })
  314. .remove();
  315. // Store the old positions for transition.
  316. nodes.forEach(function(d){
  317. d.x0 = d.x;
  318. d.y0 = d.y;
  319. });
  320. // Creates a curved (diagonal) path from parent to the child nodes
  321. function diagonal(s, d) {
  322. path = `M ${s.y} ${s.x}
  323. C ${(s.y + d.y) / 2} ${s.x},
  324. ${(s.y + d.y) / 2} ${d.x},
  325. ${d.y} ${d.x}`;
  326. return path;
  327. }
  328. // Toggle children on click.
  329. function click(d) {
  330. //has children, so close them
  331. if (d.children) {
  332. d._children = d.children;
  333. d.children = null;
  334. //update(d);
  335. } else {
  336. //dont have children, so open them
  337. d.children = d._children;
  338. d._children = null;
  339. //update(d);
  340. }
  341. update(d);
  342. toggleBars(d);
  343. toggleRadars(d);
  344. }
  345. }
  346. function toggleBars(d) {
  347. // show bars only on last level
  348. if (d.children) {
  349. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .bars")
  350. .attr("fill", "none");
  351. d.children.forEach(toggleBars);
  352. } else {
  353. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .bars")
  354. .attr("fill", "blue");
  355. }
  356. }
  357. function toggleRadars(d) {
  358. // show bars only on last level
  359. if (d.children) {
  360. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .radarArea")
  361. .style("fill", "none");
  362. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .radarLegend")
  363. .style("fill", "none");
  364. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .radarStroke")
  365. .style("stroke", "none");
  366. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .radarLine")
  367. .style("stroke", "none");
  368. d.children.forEach(toggleRadars);
  369. } else {
  370. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .radarArea")
  371. .style("fill", "#EDC951");
  372. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .radarLegend")
  373. .style("fill", "black");
  374. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .radarStroke")
  375. .style("stroke", "black");
  376. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .radarLine")
  377. .style("stroke", "#CDCDCD");
  378. }
  379. }
  380. var yCap = 100;
  381. var current_node = 0;
  382. function updateScale(step) {
  383. yCap = yCap + step;
  384. yScaleb
  385. .range([0, yCap]);
  386. }
  387. function resetScale() {
  388. yScaleb
  389. .range([0, 100]);
  390. }
  391. function reScaleBars(d) {
  392. if (current_node != (d.id -1)) {
  393. resetScale();
  394. yCap = 100;
  395. current_node = d.id -1;
  396. }
  397. if (d3.event.deltaY < 0) {
  398. updateScale(20);
  399. } else {
  400. updateScale(-20);
  401. }
  402. drawBars(d);
  403. }
  404. function resetBars(d) {
  405. resetScale();
  406. yCap = 100;
  407. current_node = d.id -1;
  408. drawBars(d);
  409. }
  410. function drawBars(d) {
  411. dendrogram_plot.selectAll("#node-" + (d.id -1) + " .bars")
  412. .data(function() {
  413. if (d.data.name == "Brasil") {
  414. return bardata[0].value;
  415. }
  416. for (var i = 1; i < bardata.length; i++) {
  417. if (d.data.name == bardata[i].name[1]) {
  418. if (d.ancestors()[1].data.name == bardata[i].name[0]) {
  419. return bardata[i].value;
  420. }
  421. }
  422. }
  423. return 0;
  424. })
  425. .attr("x", function(d, i) {
  426. return 13 + xScale(i);
  427. })
  428. .attr("y", function(d) {
  429. return 13 -yScaleb(d);
  430. })
  431. .attr("width", xScale.bandwidth())
  432. .attr("height", function(d) {
  433. return yScaleb(d);
  434. });
  435. }
  436. function showToolTip(d) {
  437. var tooltip = d3.select("#tooltip_area");
  438. var text = "";
  439. if (d.data.name == "Brasil") {
  440. for(var j = 0; j < total; j++) {
  441. text = text + radardata[0].value[j].axis + ": " + radardata[0].value[j].value + "<br/>";
  442. }
  443. tooltip.html(d.data.name + "<br/>" + text);
  444. tooltip.transition();
  445. return tooltip.style("visibility", "visible").style("opacity", 1);
  446. }
  447. for (var i = 1; i < radardata.length; i++) {
  448. if (d.data.name == radardata[i].name[1]) {
  449. if (d.ancestors()[1].data.name == radardata[i].name[0]) {
  450. for(var k = 0; k < total; k++) {
  451. if(radardata[i].value[k]) {
  452. text = text + radardata[i].value[k].axis + ": " + radardata[i].value[k].value + "<br/>";
  453. }
  454. }
  455. tooltip.html(d.data.name + "<br/>" + text);
  456. tooltip.transition();
  457. return tooltip.style("visibility", "visible").style("opacity", 1);
  458. }
  459. }
  460. }
  461. return 0;
  462. }
  463. function hideToolTip(d) {
  464. return d3.select("#tooltip_area").style("visibility", "hidden");
  465. }
  466. });