Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active March 24, 2017 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbostock/1080941 to your computer and use it in GitHub Desktop.
Save mbostock/1080941 to your computer and use it in GitHub Desktop.
Force-Directed Layout from XML
license: gpl-3.0
<?xml version="1.0" encoding="ISO-8859-1"?>
<flare>
<analytics>
<cluster>
<agglomerativeCluster>3938</agglomerativeCluster>
<communityStructure>3812</communityStructure>
<mergeEdge>743</mergeEdge>
</cluster>
<graph>
<test>3343</test>
<mmmm>3353</mmmm>
<lalala>454</lalala>
</graph>
<optimization>
<AspectRatio>7074</AspectRatio>
</optimization>
</analytics>
</flare>
<!DOCTYPE html>
<style>
.link line {
stroke: #aaa;
}
.node circle {
pointer-events: all;
stroke: none;
stroke-width: 40px;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var radius = d3.scaleSqrt()
.domain([0, 20000])
.range([0, 20]);
var link = svg.append("g")
.attr("class", "link")
.selectAll("line");
var node = svg.append("g")
.attr("class", "node")
.selectAll("circle");
var drag = d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink())
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2))
.on("tick", ticked)
.stop();
d3.xml("flare.xml", function(error, document) {
if (error) throw error;
var nodes = d3.select(document).selectAll("*").nodes(),
links = nodes.slice(1).map(function(d) { return {source: d, target: d.parentNode}; });
link = link.data(links).enter().append("line");
node = node.data(nodes).enter().append("circle")
.attr("r", function(d) { return radius(d.textContent) || 5; })
.call(drag);
node.append("title")
.text(function(d) { return d.tagName; });
simulation.nodes(nodes);
simulation.force("link").links(links);
simulation.restart();
});
function ticked() {
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("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x, d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x, d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null, d.fy = null;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment