Published
Edited
Jun 22, 2022
1 star
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height);

cancelAnimationFrame(config.animReqId);
const centers = [width / 2.4, width / 2, width / 1.6]
const duration = 4
const foci = 2 //group to add new nodes to

nodes.forEach(d=>{
// assign initial coordinates to each node
d.targetX = centers[d.band-1]
d.targetY = height/2
})

simulation
.nodes(nodes)
.stop()
for (let i = 0; i < 100; i++) {
simulation.tick();
}

update(svg, nodes)
let nodesToAdd = []
for (let i = 0; i < 100; i++) {
nodesToAdd.push({
id: nodes.length + i,
//assign initial coordinates, which is the centroid of the group new node belongs to
x: centers[foci-1],
y: height/2,
delay: Math.random() * (duration * 1000),
//assign final coordinates, which is the centroid of the group new node belongs to
targetX: centers[foci-1],
targetY : height/2,
band: foci,
radius: defaults.RADIUS
});
}

config.animReqId = requestAnimationFrame((t) => animate(t, nodesToAdd, svg));

return svg.node();
}
Insert cell
function animate(time, nodesToAdd, svg) {
if (!config.startTime) {
config.startTime = time;
}

const progress = time - config.startTime;
const nodes = simulation.nodes()
update(svg, nodes, 'transition_by_default', {DURATION: 350})
const newNodes = [];
for (let i = 0; i < nodesToAdd.length; i++) {
const node = nodesToAdd[i];
if (node.delay < progress) {
newNodes.push(node)
nodesToAdd.splice(i, 1);
i--;
}
}

simulation.nodes(nodes.concat(newNodes))
.alpha(defaults.ALPHA)
.tick();

config.ticks++;

if (config.ticks < 500 || nodesToAdd.length > 0) {
config.animReqId = requestAnimationFrame((t) => animate(t, nodesToAdd, svg));
}
}
Insert cell
simulation = d3.forceSimulation()
.nodes([])
.force('charge', d3.forceManyBody().strength(defaults.FORCEMANYBODY_STRENGTH))
.force('collision', d3.forceCollide().radius(defaults.COLLISION_RADIUS).strength(defaults.COLLISION_STRENGTH))
.force('x', d3.forceX().strength(1).x(d => d.targetX))
.force('y', d3.forceY().strength(1).y(d => d.targetY))
.stop()
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more