Published
Edited
Apr 4, 2022
Insert cell
Insert cell
Insert cell
{
const w = 1800,
h = 1800,
n = 10000,
max = 5,
min = 1;

const div = DOM.element('div');

const data = [...new Array(n)].map((d,i)=>{
const rand = Math.floor(Math.random() * (max - min)) + min;
return {"index":i,"r":rand};
})

const beforeData = {...data}; // copy the data before running the simulation

const simulation = d3.forceSimulation()
.nodes(data)
.force('center', d3.forceCenter(w / 2, h / 2))
.force('charge', d3.forceManyBody().strength(-1))
.on("tick",simulationTicked)
.on("end",simulationEnd)

function simulationTicked() {
console.log("start");
simulation.stop();
while (simulation.alpha() > simulation.alphaMin()) {
simulation.tick();
}
}

function simulationEnd() {
console.log("end");
const b1 = makeDownloadButton(beforeData, 'beforeData.json');
const b2 = makeDownloadButton(data, 'afterData.json');
div.appendChild(b1);
div.appendChild(b2);
}
function makeDownloadButton(data, filename) {
if (!data) throw new Error('Array of data required as first argument');
const downloadData = new Blob([JSON.stringify(data, null, 2)], {type: "application/json"});
const button = DOM.download(
downloadData,
filename,
`Download ${filename}`
);
return button;
}

return div;
}
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