score:56
Well I could find the solution browsing through, posting it here for anyone needing help on this topic. The idea is to create an object of the graph and playing around with the nodes and links arrays. The JS code goes as:
var graph;
function myGraph(el) {
// Add and remove elements on the graph object
this.addNode = function (id) {
nodes.push({"id":id});
update();
};
this.removeNode = function (id) {
var i = 0;
var n = findNode(id);
while (i < links.length) {
if ((links[i]['source'] == n)||(links[i]['target'] == n))
{
links.splice(i,1);
}
else i++;
}
nodes.splice(findNodeIndex(id),1);
update();
};
this.removeLink = function (source,target){
for(var i=0;i<links.length;i++)
{
if(links[i].source.id == source && links[i].target.id == target)
{
links.splice(i,1);
break;
}
}
update();
};
this.removeallLinks = function(){
links.splice(0,links.length);
update();
};
this.removeAllNodes = function(){
nodes.splice(0,links.length);
update();
};
this.addLink = function (source, target, value) {
links.push({"source":findNode(source),"target":findNode(target),"value":value});
update();
};
var findNode = function(id) {
for (var i in nodes) {
if (nodes[i]["id"] === id) return nodes[i];};
};
var findNodeIndex = function(id) {
for (var i=0;i<nodes.length;i++) {
if (nodes[i].id==id){
return i;
}
};
};
// set up the D3 visualisation in the specified element
var w = 500,
h = 500;
var vis = d3.select("#svgdiv")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("id","svg")
.attr("pointer-events", "all")
.attr("viewBox","0 0 "+w+" "+h)
.attr("perserveAspectRatio","xMinYMid")
.append('svg:g');
var force = d3.layout.force();
var nodes = force.nodes(),
links = force.links();
var update = function () {
var link = vis.selectAll("line")
.data(links, function(d) {
return d.source.id + "-" + d.target.id;
});
link.enter().append("line")
.attr("id",function(d){return d.source.id + "-" + d.target.id;})
.attr("class","link");
link.append("title")
.text(function(d){
return d.value;
});
link.exit().remove();
var node = vis.selectAll("g.node")
.data(nodes, function(d) {
return d.id;});
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.call(force.drag);
nodeEnter.append("svg:circle")
.attr("r", 16)
.attr("id",function(d) { return "Node;"+d.id;})
.attr("class","nodeStrokeClass");
nodeEnter.append("svg:text")
.attr("class","textClass")
.text( function(d){return d.id;}) ;
node.exit().remove();
force.on("tick", function() {
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
});
// Restart the force layout.
force
.gravity(.05)
.distance(50)
.linkDistance( 50 )
.size([w, h])
.start();
};
// Make it all go
update();
}
function drawGraph()
{
graph = new myGraph("#svgdiv");
graph.addNode('A');
graph.addNode('B');
graph.addNode('C');
graph.addLink('A','B','10');
graph.addLink('A','C','8');
graph.addLink('B','C','15');
}
score:0
In addition to calling drawGraph()
in the ready function, you can also embed the posted code inside an inline <script></script>
block.
This is how most of the tutorials on the d3 site handle it.
score:13
I took Rahuls great example, made some changes, and posted a bl.ock complete with animation over time if anyone is interested in a fully functioning example. Adding/removing links/nodes really should be easier than this, but still pretty cool.
http://bl.ocks.org/ericcoopey/6c602d7cb14b25c179a4
Source: stackoverflow.com
Related Query
- Updating links on a force directed graph from dynamic json data
- d3js Force Directed Graph - Click on node to popup infobox which read from JSON
- How to fetch data from json file to draw a dynamic graph by using d3.js
- Updating nodes and links with labels in d3 force directed network graph is not removing the nodes properly
- Unable to Delete links from a D3 force directed graph with arrows
- d3.js tool tip on a force directed graph not displaying complete data while hovering over links
- D3.js Force Directed Graph with Json - Create graph specifying link distance from all nodes
- how to import php script that convert mysql data to json format, from d3.json function in force directed layout
- Add text/label onto links in D3 force directed graph
- D3 highlight selected node, and its links to parent and ancestors in a force directed graph
- Constructing Force Directed Graphs From Only Link Data
- Updating the data of a pack layout from JSON call and redrawing
- Adding label to the links in D3 force directed graph
- How to add a dynamic legend to a D3 force directed graph in Apex?
- How to render links as elbow connectors in d3 force directed graph
- D3.js - building a force directed hierachical tree from csv data
- Collapsible D3 force directed graph with non-tree data
- D3v4 force directed graph - localStorage disconnects links and nodes
- How to expand child from JSON, load data after click parent - D3.Js - force directed layout
- how to highlight(change color) of all connected(neighbours) nodes and links in a d3 force directed graph
- Node generation from json data for force layout
- Missing links in force directed graph
- d3 force directed graph using node names for links
- End points of the links of the force directed graph always stuck to left corner of the rectangular node
- D3.js - Changing force directed graph node from circle to svg:rect
- JSON data from Django to D3 graph
- Drawing links that do not affect the physics of a force directed graph
- How can I use crossfilter to filter graph data and visualize them on a force directed graph?
- Removing duplicate edges from an array for a d3 force directed graph
- Show tool-tip on links of force directed graph in d3js
More Query from same tag
- How to use d3.js graphs in Ext.js?
- Image flicker when user tries to pan
- How to zoom only on the X axis in a line chart in d3.js (v7)
- Drawing a sector of sunburst diagram using d3.js
- D3.js: use d3.nest() adding keys dynamically
- Morphing SVG line from straight to expanded
- Bar chart scale
- d3.js: Map X-axis labels to some key and render key-label table to avoid overlapping?
- Label for d3 donut chart
- create a radial chart with d3.js
- how to get screen coords using projection with a multipolygon in d3
- D3 Sankey Diagram: Adding New Node and Link with Transition
- D3.js: Get parentNode after append
- How to split area-spline area in different colors in c3js
- How to remove the border on the hover element in nvd3
- MongoDB Collection as data source for cs.js in Meteor app
- DataMap/D3 - how to reset zoom?
- How to get common child node in D3.js Force-based Labeled Layout Graph
- Remove Double-Click Zoom D3
- How do you increase padding at different levels of d3.js's packed circle layout?
- Grab the element with d3js
- Changing 'children' node in json
- Defining Regions in a US Map Using D3.js
- how to use <h1> in c3.js div?
- How to create a D3 Bubble Chart in straigth line path?
- How to embed bitmap into D3js generated SVG code?
- d3.js v5 changing an element from an imported svg
- What happened to d3.interpolateGnBu
- Is there any compatibility between HTML canvas and SVG or are they completely separate beasts?
- How to display country names on globe d3.js