Published
Edited
Jul 18, 2019
Insert cell
md`# Force-DirectedGraph with Clustering`
Insert cell
chart = {
const links = data.links.map(d => Object.create(d));
const nodes=pack().leaves()


const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.data.id).strength(0.05))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2))
.force("cluster", forceCluster());

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

const link = svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.join("line")


const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 5)
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("fill", color)
.call(drag(simulation));

node.append("title")
.text(d => d.id);

simulation.on("tick", () => {
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("cx", d => d.x)
.attr("cy", d => d.y);
});

invalidation.then(() => simulation.stop());

return svg.node();
}
Insert cell
drag = simulation => {
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;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
Insert cell
function forceCluster() {
const strength = 0.1;
let nodes;
function force(alpha){
const centroids = d3.rollup(nodes, centroid, d=>d.data.group)
const l = alpha * strength;
for (const d of nodes) {
const {x: cx, y: cy} = centroids.get(d.data.group);
d.vx -= ( d.x - cx)*l
d.vy -= ( d.y - cy)*l
}

}
force.initialize = _ => nodes = _;
return force;
}
Insert cell
function centroid(nodes) {
let x = 0;
let y = 0;
let z = 0;
for (const d of nodes) {
let k = 5 ** 2;
x += d.x * k;
y += d.y * k;
z += k;
}
return {x: x / z, y: y / z};
}
Insert cell
pack = () => d3.pack()
.size([width, height])
.padding(1)
(d3.hierarchy(rawNodes)
.sum(d => d.numberOfCitations))
Insert cell
color = {
const scale = d3.scaleOrdinal(d3.schemeCategory10);
return d => scale(d.data.group);
}
Insert cell
rawNodes = ({children:Array.from( d3.group(
data.nodes,
d => d.group
), ([,children]) => ({children}))})
Insert cell
data = d3.json("https://gist.githubusercontent.com/Muhammad-Usman17/d879e2561bb6d63552d6fff0fe87d542/raw/a2a51232bd653440a457aea91d47b81824367252/data.json")
Insert cell
height = 600
Insert cell
d3 = require("d3@5", "d3-array@2")
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