Published
Edited
Mar 1, 2021
Insert cell
Insert cell
chart = {
const context = DOM.context2d(width, height);
nodes.forEach(d=>{
d.r = sizeScale(d.progetti)
})

const simulation = d3.forceSimulation(nodes)
.alphaTarget(0.01) // stay hot
.velocityDecay(0.3) // low friction
.force("x", d3.forceX()
.x(d=>d.pos.tipo ? d.pos.tipo.x : 0)
.strength(0.2))
.force("y", d3.forceY()
.y(d=>d.pos.tipo ? d.pos.tipo.y : 0)
.strength(0.2))
.force("collide", d3.forceCollide().radius(d => d.r + padding).iterations(5))
.on("tick", ticked);

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

function ticked() {
context.clearRect(0, 0, width, height);
context.save();
//context.translate(width / 2, height / 2);
for (const d of nodes) {
context.beginPath();
//console.log(colors[d.tipo])
context.fillStyle = colors[d.tipo]
//context.moveTo(d.x + d.r, d.y);
context.arc(d.x, d.y, d.r, 0, 2 * Math.PI);
context.fill();
}
context.restore();
}
// after 6 seconds, move to geographical positions
setTimeout(() => {
simulation
.alphaTarget(0.3) // stay hot
.velocityDecay(0.2) // low friction
.force("x", d3.forceX()
.x(d=>d.pos.delegazione ? d.pos.delegazione.x : 0)
.strength(0.1))
.force("y", d3.forceY()
.y(d=>d.pos.delegazione ? d.pos.delegazione.y : 0)
.strength(0.1))
.restart();
}, 6000);
// after 15 seconds, move to ambiti
setTimeout(() => {
nodes.forEach(d=>{
d.r = minRadius
})
simulation
.alphaTarget(0.3) // stay hot
.velocityDecay(0.2) // low friction
.force("x", d3.forceX()
.x(d=>d.pos.ambito ? d.pos.ambito.x : 0)
.strength(0.1))
.force("y", d3.forceY()
.y(d=>d.pos.ambito ? d.pos.ambito.y : 0)
.strength(0.1))
.force("collide", d3.forceCollide().radius(d => d.r + padding).iterations(5))
.restart();
}, 15000);

return context.canvas;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
minRadius = 2
Insert cell
maxRadius = 40
Insert cell
sizeScale = d3.scaleSqrt().domain(d3.extent(nodes.map(d=>d['progetti']))).range([minRadius, maxRadius])
Insert cell
Insert cell
Insert cell
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