D3:Learning:Force Directed Graph:Curved Edges
A starting point to clone and get investigating quickly.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
<button id='mybutton'>Add data</button>
</button>
<svg width="600" height="600"></svg>
CSS
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
fill: none;
stroke: #bbb;
stroke-width: 5px;
}
JavaScript
var graph = {
"nodes": [{
"id": "Myriel",
"group": 1
}, {
"id": "Napoleon",
"group": 1
}],
"links": [{
"source": "Napoleon",
"target": "Myriel",
"value": 1
}]
}
var dataset2 = {
}
document.getElementById('mybutton').addEventListener('click', buttonclick);
function buttonclick() {
graph.links.push({
"source": "Napoleon",
"target": "Myriel",
"value": 1
})
refreshNetwork()
}
var nodeSize = 15;
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var nodeContainer = svg.append('g').attr('id', 'nodeContainer')
var linkContainer = svg.append('g').attr('id', 'linkContainer')
var color = d3.scaleOrdinal(d3.schemeCategory20);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().distance(30).strength(0.5))
.force("charge", d3.forceManyBody())
.force('x', d3.forceX(width / 2))
.force('y', d3.forceY(height / 2))
//.force("center", d3.forceCenter(width / 2, height / 2))
.force('collision', d3.forceCollide().radius(nodeSize * 1.1))
refreshNetwork()
function refreshNetwork() {
console.log('refreshing')
console.log(graph)
console.log('nodes : ', graph.nodes)
console.log('links : ', graph.links)
var nodes = graph.nodes,
testNodes = graph.nodes.slice(),
//nodeById = d3.map(nodes, function(d) {
nodeById = d3.map(testNodes, function(d) {
return d.id;
}),
links = graph.links,
bilinks = [];
testNodes.forEach(function(d){
d.x = width/2
d.y = height/2
})
var edges = [];
links.forEach(function(e, i) {
// var sourceNode = nodes.filter(function(n) {
var sourceNode = testNodes.filter(function(n) {
return n.id === e.source;
})[0];
//var targetNode = nodes.filter(function(n) {
var targetNode = testNodes.filter(function(n) {
return n.id === e.target;
})[0];
// if theres a source and target
if (sourceNode && targetNode) {
var newLink = {
source:...