Skip to content

Instantly share code, notes, and snippets.

@marko-asplund
Last active July 12, 2017 20:49
Show Gist options
  • Select an option

  • Save marko-asplund/2e8c0ab4e9c26db08bfefcb8eac36b90 to your computer and use it in GitHub Desktop.

Select an option

Save marko-asplund/2e8c0ab4e9c26db08bfefcb8eac36b90 to your computer and use it in GitHub Desktop.
d3v4 force layout with labels
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.link {
stroke: #aaa;
}
.node {
pointer-events: all;
stroke: none;
stroke-width: 40px;
}
</style>
<svg width="960" height="600"></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");
const color = d3.scaleOrdinal(d3.schemeCategory20);
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id).distance(40))
.force("charge", d3.forceManyBody().strength(-100))
.force("center", d3.forceCenter(width / 2, height / 2));
d3.json("miserables.json", function(error, graph) {
if (error) throw error;
svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all")
.call(d3.zoom()
.scaleExtent([1 / 2, 4])
.on("zoom", zoomed));
const cont = svg.append("g")
.attr("class", "container");
const link = cont.append("g")
.attr("class", "links")
.selectAll(".link")
.data(graph.links, d => d.target.id)
.enter()
.append("line")
.attr("class", "link");
const node = cont.append("g")
.attr("class", "nodes")
.selectAll(".node")
.data(graph.nodes, d => d.id)
.enter()
.append("g")
.attr("class", "node")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
node.append("circle")
.attr("r", 10)
.attr("fill", d => color(d.group));
node.append("title")
.text(d => d.id);
node.append("text")
.attr("dy", 12)
.attr("dx", ".35em")
.text(d => d.id);
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function zoomed() {
cont.attr("transform", d3.event.transform);
};
function ticked() {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("transform", d => `translate(${d.x}, ${d.y})`);
}
});
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart()
}
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 = undefined;
d.fy = undefined;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment