Published
Edited
Jan 14, 2021
Insert cell
Insert cell
Insert cell
Insert cell
dynamicData = {
// If the data does not yet exist, initialize
if (!this) {
return {
nodes: [],
links: []
}
}
let color = nodeColor || "black"
let len = this.nodes.length
// create new nodes when nodeColor activated
if (this.nodes.length > 0) {
//randomly select another node to connect with
//let randomNode = this.nodes[Math.floor(Math.random() * len)];
let randomNode = this.nodes[0];
console.log(randomNode)
this.nodes.push({id: len, color, x: randomNode.x, y: randomNode.y})
this.links.push({source: randomNode.id, target: len, value: 1})
} else {
this.nodes.push({id: len, color})
}
return this
}
Insert cell
simulation = {
// If the simulation already exists, just alter the nodes, links, and restart
if (this) {
return this.nodes(dynamicData.nodes)
.force("link", d3.forceLink(dynamicData.links).id(d => d.id))
.restart()
}
// If the simulation doesn't yet exist, create it.
return d3.forceSimulation(dynamicData.nodes)
.force("link", d3.forceLink(dynamicData.links).id(d => d.id))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("charge", d3.forceManyBody())
.alphaDecay(0.0002).restart();
}
Insert cell
Insert cell
drag = () => {
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.0002).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
d3 = require("d3@5")
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