Last active
May 6, 2019 16:01
-
-
Save crongro/5b5f4f0cdd364414a4a57369cd9f9914 to your computer and use it in GitHub Desktop.
radial tidy tree (d3@v4, json based)
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
//idea : https://gist.github.com/mbostock/4063550 | |
/* | |
* [renderSVG function] | |
* @d3 : d3 object (version 4.13.0) | |
* @data : json data (e.g. flare.json) | |
*/ | |
export const renderSVG = (d3, data) => { | |
const svg = d3.select("svg"), | |
width = +svg.attr("width"), | |
height = +svg.attr("height"), | |
g = svg.append("g").attr("transform", "translate(" + (width / 2 + 40) + "," + (height / 2 + 90) + ")"); | |
const stratify = d3.stratify().parentId(function (d) { | |
return d.id.substring(0, d.id.lastIndexOf(".")); | |
}); | |
let radius = 932 / 2 | |
const tree = data => d3.tree() | |
.size([2 * Math.PI, radius]) | |
.separation((a, b) => (a.parent == b.parent ? 1 : 2) / a.depth)(d3.hierarchy(data)) | |
const root = tree(data); | |
const link = g.selectAll(".link") | |
.data(root.links()) | |
.enter().append("path") | |
.attr("class", "link") | |
.attr("d", d3.linkRadial() | |
.angle(function (d) { | |
return d.x; | |
}) | |
.radius(function (d) { | |
return d.y; | |
})); | |
const node = g.selectAll(".node") | |
.data(root.descendants()) | |
.enter().append("g") | |
.attr("class", function (d) { | |
return "node" + (d.children ? " node--internal" : " node--leaf"); | |
}) | |
.attr("transform", function (d) { | |
return "translate(" + radialPoint(d.x, d.y) + ")"; | |
}); | |
node.append("circle").attr("r", 2.5); | |
node.append("text") | |
.attr("dy", "0.31em") | |
.attr("x", function (d) { | |
return d.x < Math.PI === !d.children ? 6 : -6; | |
}) | |
.attr("text-anchor", function (d) { | |
return d.x < Math.PI === !d.children ? "start" : "end"; | |
}) | |
.attr("transform", function (d) { | |
return "rotate(" + (d.x < Math.PI ? d.x - Math.PI / 2 : d.x + Math.PI / 2) * 180 / Math.PI + | |
")"; | |
}) | |
.text(function (d) { | |
//return d.id.substring(d.id.lastIndexOf(".") + 1); | |
return d.data.name; | |
}); | |
function radialPoint(x, y) { | |
return [(y = +y) * Math.cos(x -= Math.PI / 2), y * Math.sin(x)]; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment