Skip to content

Instantly share code, notes, and snippets.

@mizmay
Last active December 28, 2017 01:44
Show Gist options
  • Save mizmay/a52259d45ac0b57dcf7c65c022a5dd39 to your computer and use it in GitHub Desktop.
Save mizmay/a52259d45ac0b57dcf7c65c022a5dd39 to your computer and use it in GitHub Desktop.
A Simple d3 Network Graph
license: mit
{
"Styles" : [
{
"Name" : "Interactive",
"ParentStyles" :[]
},
{
"Name" : "Base",
"ParentStyles" :[]
},
{
"Name" : "Blue",
"ParentStyles" :[]
},
{
"Name" : "Orange",
"ParentStyles" :[]
},
{
"Name" : "Purple",
"ParentStyles" :[]
},
{
"Name" : "Restaurant",
"ParentStyles" : ["Base","Interactive","Orange"]
},
{
"Name" : "Hotel",
"ParentStyles" : ["Base","Interactive","Purple"]
},
{
"Name" : "GasStation",
"ParentStyles" : ["Base","Interactive","Blue"]
}]
}
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v2.min.js?2.9.3"></script>
<style>
.link {
stroke: #aaa;
}
.node text {
stroke:#333;
cursos:pointer;
}
.node circle{
stroke:#fff;
stroke-width:3px;
fill:#555;
}
</style>
<body>
<script>
var width = 960,
height = 500
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.gravity(.05)
.distance(100)
.charge(-100)
.size([width, height]);
d3.json("graphFile.json", function(json) {
var styles = [];
json.Styles.forEach(function(s) { styles.push({name: s.Name}) });
var edges = [];
json.Styles.forEach(function(e) {
var sourceNode = styles.findIndex(function(n) {
return n.name === e.Name; });
targetNode = -1;
e.ParentStyles.forEach(function(p) {
targetNode = styles.findIndex( function(n) { return n.name === p; });
if ( targetNode >= 0 ) {
edges.push({source: sourceNode, target: targetNode, weight: 1}) }
});
console.log(edges);
});
force
.nodes(styles)
.links(edges)
.start();
var link = svg.selectAll(".link")
.data(edges)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(styles)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r","5");
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment