Published
Edited
May 25, 2020
Insert cell
Insert cell
Insert cell
dataset = [ 5, 10, 20, 45, 6, 25 ];
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
force_layout = {
//Initialize a simple force layout, using the nodes and edges in dataset
var force = d3.forceSimulation(people.nodes)
.force("charge", d3.forceManyBody())
.force("link", d3.forceLink(people.edges))
.force("center", d3.forceCenter().x(width/2).y(height/2));

var colors = d3.scaleOrdinal(d3.schemeCategory10);

const svg = d3.select(DOM.svg(width, height));

//Create edges as lines
var edges = svg.selectAll("line")
.data(people.edges)
.enter()
.append("line")
.style("stroke", "#ccc")
.style("stroke-width", 1);
//Create nodes as circles
var nodes = svg.selectAll("circle")
.data(people.nodes)
.enter()
.append("circle")
.attr("r", 10)
.style("fill", function(d, i) {
return colors(i);
})
.call(d3.drag() //Define what to do on drag events
.on("start", dragStarted)
.on("drag", dragging)
.on("end", dragEnded));

//Add a simple tooltip
nodes.append("title")
.text(function(d) {
return d.name;
});
//Every time the simulation "ticks", this will be called
force.on("tick", function() {

edges.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; });
nodes.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
//Define drag event functions
function dragStarted(d) {
if (!d3.event.active) force.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}

function dragging(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}

function dragEnded(d) {
if (!d3.event.active) force.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more