Last active
November 19, 2019 03:17
-
-
Save beekimrj/2e71997bfbfe564ef76cad20e013b32b to your computer and use it in GitHub Desktop.
It makes tree hierarchy using rectangle as a node and we can assign different color in each node. this video is made watching tutorial from https://www.youtube.com/watch?v=1DUv_OS59Uc
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
<html> | |
<head> | |
<title> Rectangle </title> | |
<script src="https://d3js.org/d3.v5.min.js"></script> | |
<style> | |
rect | |
{ | |
fill:white; | |
stroke: green; | |
stroke-width: 2px; | |
} | |
path | |
{ | |
fill:none; | |
stroke: green; | |
stroke-width: 2px; | |
} | |
text | |
{ | |
dominant-baseline:middle; | |
text-anchor:middle; | |
} | |
.bigger | |
{ | |
font-size: 15px; | |
} | |
</style> | |
</head> | |
<body> | |
<script> | |
var svg = d3.select("body").append("svg").attr("width", 900).attr("height", 600) | |
.append("g").attr("transform", "translate(50,50)"); | |
// structure of data is:- Node name, its parent and color you want to assign to that node | |
var data = [ {"child":"John", "parent":"", "color":"#ff0000"}, | |
{"child":"Aaron", "parent":"John", "color":"#00ff00"}, | |
{"child":"Kevin", "parent":"Aaron", "color":"#0000ff"}, | |
{"child":"Hannah", "parent":"John", "color":"#f0f0f0"}, | |
{"child":"Rose", "parent":"Aaron", "color":"#9996f1"}, | |
{"child":"Ann", "parent":"Kevin", "color":"#ffcc99"} | |
]; | |
var dataStructure = d3.stratify() | |
.id(function(d){return d.child;}) | |
.parentId(function(d){return d.parent}) | |
(data); | |
var treeStructure = d3.tree().size([650,300]); | |
var information = treeStructure(dataStructure); | |
// console.log(information.descendants()) ; | |
var connections = svg.append("g").selectAll("path") | |
.data(information.links()); | |
connections.enter().append("path") | |
.attr("d",function(d){ | |
return "M" + d.source.x + "," + d.source.y + "v 50 H"+ d.target.x | |
+" V" + d.target.y; | |
}); | |
var rectangles = svg.append("g").selectAll("rect") | |
.data(information.descendants()); | |
rectangles.enter().append("rect") | |
.attr("x", function(d){return d.x-40;}) | |
.attr("y", function(d){return d.y-20;}) | |
.attr("width", 80) | |
.attr("height", 40) | |
.style("fill", function(d) { return (d.data.color) }); | |
var names = svg.append("g").selectAll("text") | |
.data(information.descendants()); | |
names.enter().append("text") | |
.text(function(d){return d.data.child;}) | |
.attr("x",function(d){return d.x}) | |
.attr("y",function(d){return d.y}) | |
.classed("bigger",true); | |
// console.log(rectangles); | |
</script> | |
</body> | |
</html> |
Author
beekimrj
commented
Nov 19, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment