Last active
May 10, 2020 17:25
-
-
Save UPstartDeveloper/75f7f5390fc70484e8d307bb8b51f7cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- simulator/templates/partials/population-tree.html --> | |
<script src="https://d3js.org/d3.v5.min.js"></script> | |
<script> | |
$(document).ready(function(){ | |
// get the data on the InfectedNode instancesfrom the API, using AJAX | |
let endpoint = '/api/{{experiment.id}}/chart/infected-node/'; | |
$.ajax({ | |
method: "GET", | |
url: endpoint, | |
success: function(data){ | |
console.log(data); | |
treeChart(data); | |
}, | |
error: function(error_data){ | |
console.log('error'); | |
console.log(error_data); | |
} | |
}); | |
}) | |
// Make a Tree by using D3: https://observablehq.com/@d3/collapsible-tree | |
let treeChart = data => { | |
// tree params | |
let width = 954; | |
let radius = width / 2; | |
// make the tree | |
let tree = data => { | |
const root = d3.hierarchy(data); | |
root.dx = 10; | |
root.dy = width / (root.height + 1); | |
return d3.tree().nodeSize([root.dx, root.dy])(root); | |
} | |
// make the chart | |
let chart = () => { | |
const root = tree(data); | |
let x0 = Infinity; | |
let x1 = -x0; | |
root.each(d => { | |
if (d.x > x1) x1 = d.x; | |
if (d.x < x0) x0 = d.x; | |
}); | |
const svg = d3.select('#treeImage').append("svg") | |
.attr("viewBox", [0, 0, width, x1 - x0 + root.dx * 2]); | |
const g = svg.append("g") | |
.attr("font-family", "sans-serif") | |
.attr("font-size", 10) | |
.attr("transform", `translate(${root.dy / 3},${root.dx - x0})`); | |
const link = g.append("g") | |
.attr("fill", "none") | |
.attr("stroke", "#555") | |
.attr("stroke-opacity", 0.4) | |
.attr("stroke-width", 1.5) | |
.selectAll("path") | |
.data(root.links()) | |
.join("path") | |
.attr("d", d3.linkHorizontal() | |
.x(d => d.y) | |
.y(d => d.x)); | |
const node = g.append("g") | |
.attr("stroke-linejoin", "round") | |
.attr("stroke-width", 3) | |
.selectAll("g") | |
.data(root.descendants()) | |
.join("g") | |
.attr("transform", d => `translate(${d.y},${d.x})`); | |
node.append("circle") | |
.attr("fill", d => d.children ? "#555" : "#999") | |
.attr("r", 2.5); | |
node.append("text") | |
.attr("dy", "0.31em") | |
.attr("x", d => d.children ? -6 : 6) | |
.attr("text-anchor", d => d.children ? "end" : "start") | |
.text(d => d.data.name) | |
.clone(true).lower() | |
.attr("stroke", "white"); | |
return svg.node(); | |
} | |
chart(); | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment