Graph data dynamic updates using 3d-force-graph. Clicking on a node removes it from the graph.
Last active
August 8, 2024 19:56
-
-
Save vasturiano/2f602ea6c51c664c29ec56cbe2d6a5f6 to your computer and use it in GitHub Desktop.
Dynamic 3D Graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<head> | |
<script src="//unpkg.com/3d-force-graph"></script> | |
<style> | |
body { margin: 0; } | |
</style> | |
</head> | |
<body> | |
<div id="3d-graph"></div> | |
<script> | |
const initData = { | |
nodes: [ {id: 0 } ], | |
links: [] | |
}; | |
const elem = document.getElementById("3d-graph"); | |
const Graph = ForceGraph3D()(elem) | |
.enableNodeDrag(false) | |
.onNodeHover(node => elem.style.cursor = node ? 'pointer' : null) | |
.onNodeClick(removeNode) | |
.graphData(initData); | |
setInterval(() => { | |
const { nodes, links } = Graph.graphData(); | |
const id = nodes.length; | |
Graph.graphData({ | |
nodes: [...nodes, { id }], | |
links: [...links, { source: id, target: Math.round(Math.random() * (id-1)) }] | |
}); | |
}, 1000); | |
// | |
function removeNode(node) { | |
let { nodes, links } = Graph.graphData(); | |
links = links.filter(l => l.source !== node && l.target !== node); // Remove links attached to node | |
nodes.splice(node.id, 1); // Remove node | |
nodes.forEach((n, idx) => { n.id = idx; }); // Reset node ids to array index | |
Graph.graphData({ nodes, links }); | |
} | |
</script> | |
</body> |
How do I achieve const { nodes, links } = Graph.graphData();
for ReactForceGraph2d
?
Thanks, @vasturiano for this library! I'm wondering if there is a way to separately style the animated transitions of entering, updating, and exiting nodes, such as with D3's selection.join. If not, would a decent workaround be to add the new dataset (B) to the old (A), but color A & B differently, letting them coexist for a few milliseconds, and then remove B? Many thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you very much @vasturiano for this library it is really helpful and good example to show hoe it's work .