I've found a nice example of a force directed graph in d3.js version 7 that I wanted to extend: https://observablehq.com/@brunolaranjeira/d3-v6-force-directed-graph-with-directional-straight-arrow
I now want to have a button, that inserts some new nodes and the according links into the graph. Unfortunately this does not work and I don't find any documentation or good examples for this.
I've found this description for adding data, but it's fairly old and not working with d3.js v7: https://stackoverflow.com/a/20702436/3920200
Any ideas or code examples on how to add nodes and links to an existing graph with nice rerendering?
I've added an example where I tried to add some data to the existing arrays, but I don't whether even the approach is correct.
const graph = {
"nodes": [
{ "id": "A", "group": 1 },
{ "id": "B", "group": 2 },
{ "id": "C", "group": 2 },
{ "id": "D", "group": 3 },
{ "id": "E", "group": 3 }
],
"links": [
{ "source": "A", "target": "B", "value": 1 },
{ "source": "A", "target": "C", "value": 2 },
{ "source": "B", "target": "D", "value": 2 },
{ "source": "A", "target": "E", "value": 4 },
{ "source": "A", "target": "D", "value": 2 }
]
}
const links = graph.links.map(d => Object.create(d));
const nodes = graph.nodes.map(d => Object.create(d));
const types = Array.from(new Set(links.map(d => d.type)));
const simulation = d3
.forceSimulation(nodes)
.force(
'link',
d3.forceLink(links).id(d => d.id),
)
.force('charge', d3.forceManyBody().strength(-300))
.force('x', d3.forceX())
.force('y', d3.forceY())
.force(
'collide',
d3.forceCollide(d => 65),
)
.force('center', d3.forceCenter(500, 500));
const drag = (simulation) => {
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return d3.drag().on('start', dragstarted).on('drag', dragged).on('end', dragended);
};
const svg = d3
.select('.container')
.append('svg')
.attr('preserveAspectRatio', 'xMinYMin meet')
.attr('viewBox', '0 0 1000 1000')
.classed('svg-content', true)
.call(d3.zoom().on('zoom', e => svg.attr('transform', e.transform)))
.append('g');
// Per-type markers, as they don't inherit styles.
svg
.append('defs')
.selectAll('marker')
.data(types)
.join('marker')
.attr('id', d => `arrow-${d}`)
.attr('viewBox', '0 -5 10 10')
.attr('refX', 38)
.attr('refY', 0)
.attr('markerWidth', 6)
.attr('markerHeight', 6)
.attr('orient', 'auto')
.append('path')
.attr('fill', '262626')
.attr('d', 'M0,-5L10,0L0,5');
const link = svg
.append('g')
.attr('fill', 'none')
.attr('stroke-width', 1.5)
.selectAll('path')
.data(links)
.join('path')
.attr('stroke', 'green') //d => color(d.type))
.attr('marker-end', d => `url(${new URL(`#arrow-${d.type}`, location)})`);
const node = svg
.append('g')
.attr('fill', 'currentColor')
.attr('stroke-linecap', 'round')
.attr('stroke-linejoin', 'round')
.selectAll('g')
.data(nodes)
.join('g')
.call(drag(simulation));
node
.append('circle')
.attr('stroke', 'white')
.attr('stroke-width', 1.5)
.attr('r', 25)
.attr('fill', d => '#6baed6');
node
.append('text')
.attr('x', 30 + 4)
.attr('y', '0.31em')
.text(d => d.id)
.clone(true)
.lower()
.attr('fill', 'none')
.attr('stroke', 'white')
.attr('stroke-width', 3);
node.on('dblclick', (e, d) => console.log(nodes[d.index]));
const clickHandler = a => {
nodes.push({
id: 'F',
group: 1
});
nodes.push({
id: 'G',
group: 1
});
links.push({
source: 'A',
target: 'F',
value: 2
});
links.push({
source: 'F',
target: 'G',
value: 2
});
};
simulation.on('tick', () => {
link.attr('d', d => `M${d.source.x},${d.source.y}A0,0 0 0,1 ${d.target.x},${d.target.y}`);
node.attr('transform', d => `translate(${d.x},${d.y})`);
});
// invalidation.then(() => simulation.stop());
d3.select('.container').append('button').attr('class', 'my-button').text('add data').on('click', clickHandler);
const color = (types) => d3.scaleOrdinal(types, d3.schemeCategory10);
.my-button {
position: absolute;
top: 0;
left: 0;
<script src="https://d3js.org/d3.v7.min.js"></script>
<div class="container"></div>