Published
Edited
Jul 19, 2020
6 stars
Force-Directed Graph with Circle Packing
Temporal Network Visualization
Insert cell
Insert cell
chart = {
const k = 10
let clicked = false
const links = data.links.map(d => Object.create(d));
const nodes = data.nodes.map(d => Object.create(d));

const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id))
.force("charge", d3.forceManyBody().strength(-100))
.force("collide", d3.forceCollide(function (d) { return nodeRadiusScale(d.value) }))
.force("center", d3.forceCenter(width / 2, height / 2));

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

const link = svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(links)
.join("line")
.attr("stroke-width", d => Math.sqrt(d.value));

const nodeG = svg.append("g")
.selectAll("g")
.data(nodes)
.join("g")
.call(drag(simulation))
.on("click", d => (zoom(d), d3.event.stopPropagation()));
nodeG.append('circle')
.attr("r", d => nodeRadiusScale(d.value))
.attr("fill", color)
nodeG.append('text')
.style("fill", "black")
.attr("font-size", "0.8em")
.attr("text-anchor", "middle")
.attr("alignment-baseline", "middle")
.attr("dy", d => -nodeRadiusScale(d.value)-5)
.text(d=>d.id)
nodeG.append('g')
.each(function (d) {
drawHexagons(
d3.select(this),
[{ key: d.id, values: d.value, pairs: d.pairs }],
{
width: nodeRadiusScale(d.value),
height: nodeRadiusScale(d.value),
nodeColor: 'white',
borderColor: 'black',
nodeTextColor: 'black',
}
)
})

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);

nodeG.attr("transform", d => `translate(${d.x}, ${d.y})`)
});

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

function zoom(focus) {
const transition = svg.transition()
.duration(750)
.attr("transform", function(){
clicked = !clicked
if(clicked){
return `translate(${-(focus.x-width/2)*k},${-(focus.y-height/2)*k})scale(${k})`
} else {
return `translate(${0},${0})})scale(1)`
}
});
}

return svg.node();
}
Insert cell
data = FileAttachment("miserables.json").json()
Insert cell
data['nodes'].forEach((d,i)=>{
d.value = Math.floor(Math.random() * 5)
})
Insert cell
data['nodes'].forEach((d,i)=>{
d.pairs = d.value > 1 ? getPicks(d3.range(0,d.value)) : []
})
Insert cell
function getPicks(names) {
return names.slice(0).sort(function(){ return Math.random()-0.5 }).map(function(name, index, arr){
return [name.toString(), arr[(index+1)%arr.length].toString()]
});
}
Insert cell
getPicks(d3.range(0,10))
Insert cell
height = 600
Insert cell
color = {
const scale = d3.scaleOrdinal(d3.schemeCategory10);
return d => scale(d.group);
}
Insert cell
nodeRadiusScale = d3.scaleSqrt().domain([0, 50]).range([10, 50])
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 drawHexagons(nodeElement, parentIds, options) {

const nodeColor = options.nodeColor
const borderColor = options.borderColor
const nodeTextColor = options.nodeTextColor
const width = options.width
const height = options.height
const data = getData(parentIds, width * 2, height * 2)
console.log(data, parentIds[0].pairs)
const nodeData = nodeElement.selectAll("g").data(data)

const nodesEnter = nodeData
.enter()
.append("g")
.attr("id", (d, i) => "node-group-" + i)
.attr("transform", (d) => `translate(${d.x - width},${d.y - height})`)
nodesEnter
.filter((d) => d.height === 0)
.append("circle")
.attr("class", "node pie")
.attr("r", (d) => 5)
.attr("stroke", borderColor)
.attr("stroke-width", 1)
.attr("fill", "white")

nodesEnter
.filter((d) => d.height === 0)
.append("text")
.style("fill", "black")
.attr("font-size", "0.8em")
.attr("text-anchor", "middle")
.attr("alignment-baseline", "middle")
.attr("dy", -7)
.text(d=>d.data.id)
const linkData = nodeElement.selectAll("line").data(parentIds[0].pairs)

const linksEnter = linkData
.enter()
.append("line")
.attr("class", "node line")
.attr("x1", (d,i) => data.find(el=>el.data.id === d[0]).x - width)
.attr("y1", (d,i) => data.find(el=>el.data.id === d[0]).y - height)
.attr("x2", (d,i) => data.find(el=>el.data.id === d[1]).x - width)
.attr("y2", (d,i) => data.find(el=>el.data.id === d[1]).y - height)
.attr("stroke", borderColor)
.attr("stroke-width", 1)
.attr("fill", "none")

}
Insert cell
function getData(parentIDs, width, height) {

var rawData = []
rawData.push({ id: "root" })
parentIDs.forEach((d) => {
rawData.push({ id: d.key, parentId: "root", size: d.values })
d3.range(0, d.values).forEach((el) => {
rawData.push({
id: el,
parentId: d.key,
size: 1
})
})
})
const vData = d3.stratify()(rawData)
const vLayout = d3.pack().size([width, height]).padding(10)
const vRoot = d3.hierarchy(vData).sum(function (d) {
return d.data.size
})
const vNodes = vLayout(vRoot)
const data = vNodes.descendants().slice(1)

return data
}
Insert cell
d3 = require("d3@5")
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