Skip to content

Instantly share code, notes, and snippets.

@denisemauldin
Created June 25, 2018 23:16
Show Gist options
  • Save denisemauldin/7e597186612b2baa04a7f0a2f31b4a8b to your computer and use it in GitHub Desktop.
Save denisemauldin/7e597186612b2baa04a7f0a2f31b4a8b to your computer and use it in GitHub Desktop.
d3-force playground
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-force.v1.min.js"/></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
var nodes =
[
{"id": "y"},
{"id": "a"},
{"id": "e"}
]
var links =
[
{"source": 0, "target": 1},
{"source": 0, "target": 2},
{"source": 1, "target": 2}
]
var simulation = d3.forceSimulation(nodes)
.force("charge", d3.forceManyBody())
.force("link", d3.forceLink(links).distance(100))
.force("collide", d3.forceCollide().radius(function(d) { return 10;}))
.force("center", d3.forceCenter(960/2, 500/2))
.on('tick', updateGraph);
// i want arrows!
svg.append("svg:defs").selectAll("marker")
.data(["end"])
.enter().append("svg:marker")
.attr("id", "arrow")
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0, -5L10,0L0,5");
var l = svg.append("g")
.selectAll("links")
.data(links)
.enter()
.append("line")
.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;})
.attr("stroke", "black")
.attr("marker-end", "url(#arrow)");
var cir = svg.append("g")
.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("cx", function(d){return d.x;})
.attr("cy", function(d){return d.y;})
.attr("r", 10);
var n = svg.append("g")
.selectAll("text")
.data(nodes)
.enter()
.append("text")
.attr("x", function(d){return d.x;})
.attr("y", function(d){return d.y;})
.text(function(d){return d.id;});
function updateGraph(){
l
.attr("stroke", "black")
.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;})
.attr("marker-end", "url(#arrow)");
cir
.attr("cx", function(d){return d.x;})
.attr("cy", function(d){return d.y;})
.attr("r", 10)
.attr("fill", "blue")
.attr("fill-opacity", 0.1);
n
.attr("x", function(d){return d.x;})
.attr("y", function(d){return d.y;})
.text(function(d){return d.id;});
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment